예시1)
const hi = <p>Hi</p>;
예시2) - JSX - Nesting
const Login = () => {
const [id, setID] = useState("");
const saveUserID = (event) => {
setID(event.target.value);
};
return(
<div>
<input
className="input_e-mail"
type="text"
placeholder="이메일"
value={id}
onChange={saveUserID}
></input>
</div>
);
}.
import React from 'react'
const Greetings = () => {
const name = '김개발';
return (
<h1>{name}님, Welcome to Wecode!</h1>
);
};
export default Greetings;
// HTML
<h1 class="greetings">Welcome to Wecode!</h1>
// JSX
<h1 className="greetings">Welcome to Wecode!</h1>
// JS
const title = document.getElementsByClassName('title')[0];
title.addEventListener('click', handleClick);
// JSX
<h1 className="title" onClick={handleClick}>Welcome to Wecode!</h1>
// HTML
<h1 style="color:red;background-image:yellow">Welcome to Wecode!</h1>
// JSX
<h1 style={{ color: "red", backgroundImage: "yellow" }}>
Welcome to Wecode!
</h1>
🚨 주의사항
// JSX
<div className="login">
<div className="logo">
<img className="logo_wecode01" src={logo1} alt="위코드 로고1"></img>
<img className="logo_wecode02" src={logo2} alt="위코드 로고2"></img>
</div>
</div>
// Bad : 에러 발생
const Greetings = () => {
return (
<h1>김개발님!</h1>
<h2>위코드에 오신 걸 환영합니다!</h2>
);
}
// Good : 정상 동작
const Greetings = () => {
return (
// Nesting Start Tag
<div>
<h1>김개발님!</h1>
<h2>위코드에 오신 걸 환영합니다!</h2>
</div>
// Nesting End Tag
);
}
🚨 JSX 에서 하나의 태그를 Nesting 으로 만들어야 하는 이유
-> Virtual DOM에서 컴포넌트 변화를 효율적으로 비교할 수 있도록 한 컴포넌트는 하나의 DOM 트리 구조로 이루어져야 한다는 규칙이 있기 때문
// React.Fragment 사용시
const Greetings = () => {
return (
<React.Fragment>
<h1>김개발님!</h1>
<h2>위코드에 오신 걸 환영합니다!</h2>
</React.Fragment>
);
}
// 축약형 Fragment 사용시
const Greetings = () => {
return (
<>
<h1>김개발님!</h1>
<h2>위코드에 오신 걸 환영합니다!</h2>
</>
);
}