SUIN

[Raact] JSX 란 본문

React

[Raact] JSX 란

choi suin 2022. 2. 7. 18:15
728x90

 

 

jsx 없이 element를 직접 만들어 보았다 

 

[React] React DOM 다루기 (JSX 없이 element 그려보기)

VanillaJS로 element 생성 React로 element 생성 두 element를 console로 확인해보자 React 새로운 객체를 만들어냈고 그 안에 props에 children 이 들어가 있는 걸 확인할 수 있다 * React에서는 props로 넘기..

suinchoi.tistory.com

 

JSX 문법을 이용해서 간단하게 코드를 변경해보자 

 

JSX란? 

const element = <h1>Hello, world!</h1>;

- 문자도 HTML도 아닌 JavaScript 확장 문법이다 

*  전체적인 코드는 js처럼 보이지만 HTML 태그도 보이는 것을 확인할 수 있다.

* JSX를 사용하기 위해선 Babel 이 필요하다 

 

Babel ? 

- 컴파일러 : 언어 해석기 , 특정 언어를 다른 프로그래밍 언어로 옮기는 프로그램 

jsx라는 표기를 js도 이해할 수 있는 js 언어로 바벨이 변환해준다. 

 

<!-- Load Babel -->
 <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div id="root"></div>

//JSX문법전 
<script>
  const rootElement = document.getElementById("root");
   const elementReact = React.createElement(
     "h1",
     { className: "title" },
     "ReactJS "
   );
  ReactDOM.render(elementReact, rootElement);
</script>
//-----------------------------------------------
//JSX문법으로 변환 
<script type="text/babel">
  const rootElement = document.getElementById("root");
  const elementReact = <h1 className="title">ReactJS</h1>;
  ReactDOM.render(elementReact, rootElement);
</script>

 

JSX는 글자를 변수로도 넣을 수 있다 

 

스프레드 연산자를 통해서 props를 넘겨줄 수도 있다 

<script type="text/babel">
      const rootElement = document.getElementById("root");
      const text = "ReactJS";
      const titleClassName = "title";
      const props = { className: titleClassName, children: text };
      const customH1 = <h1 {...props} />;
      <!-- {...props} 는 아래 내용과 동일하다
       const customH1 = <h1 className={props.className} children={props.children}/>;-->
      const elementReact = customH1;
      ReactDOM.render(elementReact, rootElement);
</script>

변수에도 html태그모양을 담을 수 있고 모든 값들을 변수화해서 자바스크립트를 다루듯이 다룰 수 있게 해 준다.