Why JSX?
React를 공부하기 전에 JSX를 정리해 보자. JSX는 뭘까? 리액트 공식 페이지에서는 아래와 같이 JSX를 소개하고 있다.
This funny tag syntax is neither a string nor HTML.
It is called JSX, and it is a syntax extension to JavaScript. We recommend >using it with React to describe what the UI should look like. JSX may remind >you of a template language, but it comes with the full power of JavaScript.
확장된 JavaScript 문법이며, React를 사용할 때 추천한다 뭐 이런 내용인 것 같다.
구글에서 What is a JSX 라고 검색해서 나온 reactenlightenment.com 사이트에서 왜 JSX인가에 대한 답을 찾았다.
By using JSX one can write the following JSX/JavaScript code:
1 2 3 4 5 6 7 8 var nav = ( <ul id="nav"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Clients</a></li> <li><a href="#">Contact Us</a></li> </ul> );And Babel will transform it into this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 var nav = React.createElement( "ul", { id: "nav" }, React.createElement( "li", null, React.createElement( "a", { href: "#" }, "Home" ) ), React.createElement( "li", null, React.createElement( "a", { href: "#" }, "About" ) ), React.createElement( "li", null, React.createElement( "a", { href: "#" }, "Clients" ) ), React.createElement( "li", null, React.createElement( "a", { href: "#" }, "Contact Us" ) ) );
결론..JSX 문법 공부하고 리액트 열심히 공부하자!!
JSX 문법
감싸인 요소(하나의 부모 요소)
컴포넌트는 반드시 하나의 부모 요소로 감싸야 한다.
1 2 3 4 5 6 7 8
const component = () => { return ( <Fragment> <h1>First item</h1> <h1>Second item</h1> </Fragment> ); }
부모 요소의 태그는 관계없이 단 하나의 부모 요소이기만 하면 된다.
자바스크립트 표현
JSX 안에서 자바스크립트 표현식을 사용하려면 JSX 내부에서 { }로 감싸준다.
1 2 3 4 5 6 7 8
const component = () => { const text = "TEXT"; return ( <> <h1>{text}</h1> </> ); }
조건문 처리
JSX 내부에서는 자바스크립트의 if문을 사용할 수 없다. 조건문을 사용해야 할 경우 삼항 연산자 또는 논리연산을 통해 조건부 렌더링을 처리한다.
1 2 3 4 5 6 7 8
const component = () => { const text = "TEXT"; return ( <> {text === "TEXT" ? (<h1></h1>) : (<h1></h1>)} </> ) }
마치며..
그 외 undefined를 렌더링하지 않는 것, 주석처리, 인라인 스타일링, 태그 properties 는 카멜케이스 방식으로 써야한다는 점이 있었다. 필요하면 찾아보고 얼른 JSX와 React에 적응하고 싶다~~~