JSX

JSX

Posted by Seongkyun Yu on 2020-05-07
Estimated Reading Time 2 Minutes
Words 345 In Total
Viewed Times

1. JSX란

JSX는 자바스크립트 XML이다. 자바스크립트 문법의 확장판으로 리액트에서 요소를 제공한다.

JSX는 다음과 같은 특징을 갖는다.

  • 컴파일에 최적화 되어 있다.

  • 컴파일 과정이 필요하기 때문에 변환 과정에서 오류가 있다면 빌드시 오류가 발생한다.

  • 확장자는 jsx나 js를 사용할 수 있다.



2. JSX 코드의 변환 과정

JSX는 HTML코드처럼 작성하지만 바벨을 통해 자바스크립트 문법으로 변환된다. 이는 바벨 공식 홈페이지에서 시험해 볼 수 있다.

https://babeljs.io/

위 홈페이지에서 try it out 탭을 누른후, 좌측 세팅을 es2015, react 으로 맞춰줘야 정상적으로 ES5 코드로 변환 해준다.


jsx코드
1
const element = <h1 className="greeting">Hello, world!</h1>;

위의 코드는 바벨을 통해 아래와 같이 변환된다.

jsx -> 리액트
1
2
3
4
5
const element = React.createElement(
"h1",
{ className: "greeting" },
"Hello, world!"
);

최종적으로 element에는 다음과 같은 객체가 생성된다.

element
1
2
3
4
5
6
7
const element = {
type: "h1",
props: {
className: "greeting",
children: "Hello, world!",
},
};



3. JSX 문법

3.1 닫는 태그를 꼭 써야 한다.

닫는 태그 사용
1
2
3
4
5
6
7
import React from "react";

function App() {
return <div></div>;
}

export default App;
셀프 클로징 사용
1
2
3
4
5
6
7
import React from "react";

function App() {
return <div />;
}

export default App;

3.2 Fragment

리액트에서 두 개 이상의 태그를 사용할 때는 전체를 감싸는 태그가 필요하다. 이 때 div태그를 쓰지 않기 위해 Fragment를 사용한다.

함수형
1
2
3
4
5
6
7
8
9
10
11
import React, { Fragment } from "react";

function App() {
return (
<Fragment>
<ChildA />
<ChildB />
<ChildC />
</Fragment>
);
}

또는 다음과 같이 Fragment를 생략하고 사용할 수 있다.

클래스형
1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { Component } from "react";

class App extends Component {
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
}

단, 단축표기법을 사용할 경우 속성 정의나 key를 사용할 수 없다.


3.3 변수 사용

변수 사용 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React, { Component } from "react";

class App extends Component {
render() {
const title = "Hello World";
return (
<div>
<h1>{title}</h1>
</div>
);
}
}

export default App;

위 코드에서처럼 {}에 변수를 적어 사용한다.


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !