// truthy
true
{} (empty object)
[] (empty array)
32 (number, not zero)
"0", "false" (string, not empty)
//falsy
false
0, -0 (zero, minus zero)
0n (BigInt zero)
'', "", `` (empty string)
null
undefined
NaN (not a number)
&&
사용. short circuit evaluation 사용.삼항 연산자
사용. function WarningBanner(props) {
if (!props.warning) {
return null; // 렌더링 되지 않음
}
return (
<div>경고!</div>
);
}
// Toolbar.jsx
import React from "react";
const styles = {
wrapper: {
padding: 16,
display: "flex",
flexDirection: "row",
borderBottom: "1px solid grey",
},
greeting: {
marginRight: 8,
},
};
function Toolbar(props) {
const { isLoggedIn, onClickLogin, onClickLogout } = props;
return (
// &&으로 inline if
// ?으로 inline if-else 구현
<div style={styles.wrapper}>
{isLoggedIn && <span style={styles.greeting}>환영합니다!</span>}
{isLoggedIn ? (
<button onClick={onClickLogout}>로그아웃</button>
) : (
<button onClick={onClickLogin}>로그인</button>
)}
</div>
);
}
export default Toolbar;
// LandingPage.jsx
import React, { useState } from "react";
import Toolbar from "./Toolbar";
function LandingPage(props) {
// useState로 isLoggedIn state 변수 선언
const [isLoggedIn, setIsLoggedIn] = useState(false);
// onClickLogin 함수와 onClickLogout 함수 구현
const onClickLogin = () => {
setIsLoggedIn(true);
};
const onClickLogout = () => {
setIsLoggedIn(false);
};
return (
<div>
<Toolbar
isLoggedIn={isLoggedIn}
onClickLogin={onClickLogin}
onClickLogout={onClickLogout}
/>
<div style={{ padding: 16 }}>소플과 함께 하는 리액트 공부!</div>
</div>
);
}
export default LandingPage;
//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Library from './chapter_03/Library';
import Clock from './chapter_04/Clock';
import CommentList from './chapter_05/CommentList';
import NotificationList from './chapter_06/NotificationList';
import Accommodate from './chapter_07/Accommodate';
import ConfirmButton from './chapter_08/ConfirmButton';
import LandingPage from './chapter_09/LandingPage';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<LandingPage />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
배열.map();
으로 사용// 키가 빠져있는 경우
const students = [
{
name: "Mark",
},
{
name: "Peter",
},
{
name: "Andy",
},
];
function AttendanceBook(props) {
return (
<ul>
{students.map((student) => {
return <li>{student.name}</li>;
})}
</ul>
);
}
// 키를 추가해준 경우
import React from "react";
const students = [
{
id: 1,
name: "Mark",
},
{
id: 2,
name: "Peter",
},
{
id: 3,
name: "Andy",
},
];
function AttendanceBook(props) {
return (
<ul>
{students.map((student) => {
return <li key={student.id}>{student.name}</li>;
})}
</ul>
);
}
export default AttendanceBook;
<!-- html 방식 -->
<textarea>
안녕하세요
</textarea>
// jsx 방식
function RequestForm(props) {
const [value, setValue] = useState('요청사항을 입력하세요.');
const handleChange = (event) => {
setValue(event.target.value);
}
const handleSubmit = (event) => {
alert('입력한 요청사항: ' + value);
event.preventDefault();
}
return (
// textarea의 value로 넣어줘서 사용
<form onSubmit={handleSubmit}>
<label>
요청사항:
<textarea value={value} />
</label>
<button type="submit">제출</button>
</form>
);
}
각 텍스트 관련 태그(input, textarea, select)를 컨트롤드 컴포넌트로 만드는 방식은 모두 비슷하다. value로 값을 전달하고 값을 변경하고 싶을 때는 onChange에서 setValue함수를 사용하여 값을 업데이트 한다.
<input type="file" />
// hi가 input value로 들어가 있으면 수정이 안 됨
ReactDOM.render(<input value="hi" />, rootNode);
// 1초 뒤에 input value가 널인 인풋 태그가 렌더링 되면서 입력 가능한 상태로 바뀜
setTimeout(function() {
ReactDOM.render(<input value={null} />, rootNode);
}, 1000);
import React, { useState } from "react";
function SignUp(props) {
const [name, setName] = useState("");
const handleChangeName = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
alert(`이름: ${name}`);
event.preventDefault();
};
return (
// input태그의 value로 내용을 넣어줌. 여기선 name을 ""로 초기화 했었기 때문에 빈 입력으로 들어가 있음
<form onSubmit={handleSubmit}>
<label>
이름:
<input type="text" value={name} onChange={handleChangeName} />
</label>
<button type="submit">제출</button>
</form>
);
}
export default SignUp;
import React, { useState } from "react";
function SignUp(props) {
const [name, setName] = useState("");
const [gender, setGender] = useState("남자");
const handleChangeName = (event) => {
setName(event.target.value);
};
const handleChangeGender = (event) => {
setGender(event.target.value);
};
const handleSubmit = (event) => {
alert(`이름: ${name} 성별: ${gender}`);
event.preventDefault();
};
return (
// input태그의 value로 내용을 넣어줌. 여기선 name을 ""로 초기화 했었기 때문에 빈 입력으로 들어가 있음
<form onSubmit={handleSubmit}>
<label>
이름:
<input type="text" value={name} onChange={handleChangeName} />
</label>
<br />
<label>
성별:
<select value={gender} onChange={handleChangeGender}>
<option value="남자">남자</option>
<option value="여자">여자</option>
</select>
</label>
<button type="submit">제출</button>
</form>
);
}
export default SignUp;