[React] 리액트를 위한 JSX 문법
[React] 리액트를 위한 JSX 문법
JSX 문법
JavsScript + XML (확장 문법)
1. 반드시, 하나의 루트 요소만 반환해야 함!
루트 요소를 2개 이상으로 두면, 문제가 발생한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
export default function App() { return ( <div>하나</div> <div>둘</div> // ✖ ); } export default function App() { return ( <div> <div>하나</div> <div>둘</div> // ✔ </div> ); }
- 그러나, 이러한 규칙 때문에 불필요한 태그를 생성해야 한다.
따라서, 이 문제를 해결하기 위한 대책으로 React.Fragment가 있다.
1 2 3 4 5 6 7 8 9 10
import React from "react"; export default function App() { return ( <React.Fragment> <h1>App Component</h1> <h1>App Component</h1> </React.Fragment> ); }
하지만 이 방식은 React를
import해야하는 귀찮음이 존재한다.더 편한 방식인, 빈태그
<>가 있다.1 2 3 4 5 6 7 8
export default function App() { return ( <> <h1>App Component</h1> <h1>App Component</h1> </> ); }
2. 모든 태그는 닫아야 함!
다음과 같이 태그는 닫아주도록 한다.
1 2 3 4 5 6 7 8 9
export default function App() { return ( <> <h1>App Component</h1> <h1>App Component</h1> <br/> </> ); }
3. 모든 태그의 속성은 카멜 케이스로 작성해야 함!
기존의 HTML에서 작성하던 속성명은 소문자로만 구성 → 그대로 작성시, 오류.
따라서, 카멜 케이스로 작성한다!
1 2 3 4 5 6 7 8 9 10
export default function App() { return ( <> <h1>App Component</h1> <h1>App Component</h1> <br /> <input type="text" readOnly /> </> ); }
또한, 기존에 HTML에서 알고 있던 예약된 속성명을 쓸 수 없다!
따라서, 사용 시에 수정할 수 있도록한다.1 2 3 4 5 6 7 8 9 10 11
export default function App() { return ( <> <h1>App Component</h1> <h1 className="tite">App Component</h1> <br /> <label htmlFor="uname">userId: </label> <input id="uname" type="text" readOnly /> </> ); }
4. 표현식은 중괄호 {}로 출력!
데이터 바인딩을 중괄호 안에 넣어서 진행.
1 2 3 4 5 6 7 8 9 10 11 12
export default function App() { const name = "jaegeon"; return ( <> <h1>10 + 20 = {10 + 20}</h1> <h1 className="tite">{name}</h1> <br /> <label htmlFor="uname">userId: </label> <input id="uname" type="text" readOnly /> </> ); }
5. 인라인스타일 적용 시, 객체로 표현!
기존의 HTML에서 인라인스타일 적용 시, 문자열로 명시했다. → 그대로 작성시, 오류.
따라서, 문자열이 아닌 객체로 나타내도록 한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
export default function App() { const name = "jaegeon"; const style = { color: "red", fontSize: "24px", }; return ( <> <h1 style=>10 + 20 = {10 + 20}</h1> <h1 className="tite" style={style}> {name} </h1> <br /> </> ); }
6. 주석 작성법
주석은 다음과 같이 나타낼 수 있다.
1 2 3 4 5 6 7 8 9
export default function App() { return ( <> {/* 주석 작성법 */} <h1>App Component</h1> <h1>App Component</h1> </> ); }
JSX 문법이 없었다면
기존의 React에서, 문서를 작성하려면 다음과 같이 작성했음.
1 2 3 4 5 6 7 8 9
import React from "react"; export default function App() { return React.createElement( "div", { className: "title" }, React.createElement("h1", null, "App Component") ); }
같은 내용을 JSX 문법을 사용 하면? → 훨씬 간단.
1 2 3 4 5 6 7
export default function App() { return ( <div className="title"> <h1>App Component</h1> </div> ); }
This post is licensed under CC BY 4.0 by the author.