JSX란 JavaScript를 확장한 문법이다.
UI가 어떻게 생겨야 하는지 설명하기 위해 React와 함께 사용된다.
const element = <h1>Hello, world!</h1>;
<button style="background-color: blue color: white;">
Submit
</button>
다음과 같은 HTML 코드는 아래와 같은 버튼을 생성한다.
하지만 이 구문이 JSX 안에서 쓰인다면 다음과 같은 오류를 보인다.
이는 JSX에서는 속성의 값을 "" 가 아닌 {{}}로, 케밥-케이스가 아닌 카멜케이스로 사용하기 때문이다.
따라서 다음과 같이 작성하게 되면
<button style={{ backgroundColor: 'blue', color: 'white' }}>
Submit
</button>
정상 작동 하는 것을 확인 할 수 있다.
<label class="label" For="name">Enter name:</label>
다음과 같은 코드는 출력은 정상적으로 일어날 수 있으나 console을 확인해보면 warning을 보여준다.
이는 JavaScript에서 사용되는 class와 For 루프문이 혼동 될 수 있어 React가 warning을 반환해주는 것이다.
이는 다음과 같이 해결 할 수 있다.
<label className="label" htmlFor="name">Enter name:</label>
function getTime() {
return (new Date()).toLocaleTimeString()
}
// Creates a functional component
const App = () => {
return (
<div>
<div>Current Time:</div>
<h3>12:05 PM</h3>
</div>
);
}
다음과 같은 코드가 있을 때, h3 태그는 하드코딩이 되어 있다.
이는 앞서 정의한 getTime()
함수를 JSX에서 이용할 수 있다.
const App = () => {
return (
<div>
<div>Current Time:</div>
<h3>{getTime()}</h3>
</div>
);
}