JSX는 리액트에서 HTML과 자바스크립트를 함께 사용할 수 있도록 도와주는 문법 확장이다.
쉽게 말해, HTML처럼 보이는 코드를 작성하지만 실제로는 자바스크립트로 변환된다.
const element = <h1>Hello, world!</h1>;
예:
const name= 'React';
const element = <h1>Hello, {name}!</h1>;
결과:
<h1>Hello, React!</h1>
const name = 'React';
const element = <h1>Hello, {name}!</h1>;
결과:
<h1>Hello, React!</h1>
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = { firstName: 'Inje', lastName: 'Lee' };
const element = <h1>Hello, {formatName(user)}!</h1>;
결과:
<h1>Hello, Inje Lee!</h1>
사용자 유무에 따라 다른 값을 렌더링할 수도 있다.
function getGreeting(user) {
if (user) {
return <h1>Hello, {user.firstName}!</h1>;
}
return <h1>Hello, Stranger!</h1>;
}
const user = { firstName: 'React' };
const element = getGreeting(user);
JSX에서 HTML 태그의 속성을 설정하는 방법:
예:
const element = <div className="container" tabIndex="0"></div>;
결과:
<div class="container" tabindex="0"></div>
속성 값도 중괄호 {}를 사용해 동적으로 설정할 수 있다.
예:
const user = { avatarUrl: 'https://example.com/avatar.png' };
const element = <img src={user.avatarUrl} alt="User Avatar" />;
결과:
<img src="https://example.com/avatar.png" alt="User Avatar">