JSX

코린이·2023년 10월 1일

JSX(JavaScript XML)

자바스크립트 파일에서 HTML을 사용할 수 있는 React 문법

  1. JSX의 장점
  • JS와 HTML을 사용하는 것보다 코드의 양을 줄일 수 있고, 가독성이 좋으며, 직관적이다.
    버튼을 클릭했을 때 카운터가 증가하는 코드를 통해 비교해보자.
// 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를 사용하지 않으면 body태그 안에서 뼈대를 잡고, script태그 안에서 동작(버튼을 클릭했을 때 카운트 증가)에 필요한 로직을 구현하지만
  • JSX를 사용할 경우 그 과정을 통합적으로 진행하기 때문에, 개인적으로 코드를 구현할 때 UI의 배치 및 기능을 동시에 고려할 수 있다는 점이 유익했다.
  1. Babel( JSX compiler)
  • JSX는 browser에서 읽을 수 없기 때문에 Babel이라는 compiler를 통해 JS코드로 변환된다.
    Babel은 CRA(create-react-app)을 통해 project를 생성할 때 자동으로 설치된다.
// JSX를 작성하면
const element = <h1>Hello, JSX!</h1>;

// Babel이 다음과 같이 JS로 변환해준다.
const element = React.createElement("h1", null, "Hello, JSX!");
  1. JSX 문법
  • JSX는 HTML과 문법이 거의 유사하나 몇 가지 차이점이 있다.
    • 중괄호를 이용한 변수 및 동적구문 사용
      function App() {
      	const name = 'Maeng';
      	return <div>Hello, {name}!</div>;
      }
    • property 작성 방식
      // 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>





                           
                           

0개의 댓글