자바스크립트 파일에서 HTML을 사용할 수 있는 React 문법
// React문법인 JSX를 이용한 카운터
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
ReactDOM.render(<Counter />, document.getElementById('root'));
// JS와 HTML을 이용한 카운터
<!DOCTYPE html>
<html>
<head>
<title>Counter Example</title>
</head>
<body>
<div id="root">
<p>Count: <span id="count">0</span></p>
<button id="incrementButton">Increment</button>
</div>
<script>
let count = 0;
const countElement = document.getElementById('count');
const incrementButton = document.getElementById('incrementButton');
incrementButton.addEventListener('click', () => {
count++;
countElement.textContent = count;
});
</script>
</body>
</html>
// JSX를 작성하면
const element = <h1>Hello, JSX!</h1>;
// Babel이 다음과 같이 JS로 변환해준다.
const element = React.createElement("h1", null, "Hello, JSX!");
function App() {
const name = 'Maeng';
return <div>Hello, {name}!</div>;
}// JSX: 단어는 Camel Case로 구분, style property에 객체를 전달
<div className='hi' style={{color: 'green', backgroundColor: 'red'}}>
Hello!
</div>// HTML: 단어 사이에 '-' 사용
<div class='hi' style="color: green; background-color: red;">
Hello!
</div>