728x90
바벨(Babel)을 왜 사용할까?
- 자바스크립트 컴파일러
- ES6 문법을 ES5로 변경해줌
- 새로운 문법이나 타입스크립트, JSX 언어들이 모든 브라우저 환경에서 동작할 수 있도록 호환성을 지켜주는 것
- 브라우저가 JSX 문법을 이해할수 있도록 변환 해주는 것. createElement() 사용하여 컴포넌트 생성
- 코드를 작성할 때 JSX 문법으로 편리하게 작성한 뒤 변환!
- 브라우저로 확인해보면 브라우저가 읽을 수 있게 바벨로 변환한 코드는 <head> 영역에 작성되어 있음
- 예시 (두개 다 동일)
//JSX
const element = (
<h1 className="greeting">
Hello, world!
</h1>
)
//자바스크립트 createElemnet는 Web API
const element = React.createElement(
'h1',
{ className: 'greeting' },
'Hello, world!'
);
Container 를 리턴해주지 않았는데 왜 작동할까?
1. 기준 코드 -> 정상 작동
- JSX 로 컴포넌트 작성
const root = document.getElementById('root');
const Title = () => (
<h3 id='title' onMouseEnter={() => console.log('mouse enter')}>
Hello I'm a title
</h3>
);
const Button = () => (
<button
style={{
backgroundColor: 'tomato',
}}
onClick={() => console.log('im clicked')}>
Click me
</button>
);
const Container = () => (
<div>
<Title />
<Button />
{/* 컴포넌트의 첫 글자는 반드시 대문자여야 함, 만약 소문자라면
React,JSX가 HTML button 태그라고 생각하게 됨 */}
</div>
);
ReactDOM.render(<Container />, root);
- 바벨로 변환된 코드
"use strict";
var root = document.getElementById('root');
var Title = function Title() {
return /*#__PURE__*/React.createElement("h3", {
id: "title",
onMouseEnter: function onMouseEnter() {
return console.log('mouse enter');
}
}, "Hello I'm a title");
};
var Button = function Button() {
return /*#__PURE__*/React.createElement("button", {
style: {
backgroundColor: 'tomato'
},
onClick: function onClick() {
return console.log('im clicked');
}
}, "Click me");
};
var Container = function Container() {
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Title, null), /*#__PURE__*/React.createElement(Button, null));
};
ReactDOM.render( /*#__PURE__*/React.createElement(Container, null), root);
2. 의문의 코드 -> 정상 작동
- JSX 로 컴포넌트 작성
- 참고 : https://codepen.io/zxcv410/pen/zYRYeVv
const root = document.getElementById('root');
const Title = () => (
<h3 id='title' onMouseEnter={() => console.log('mouse enter')}>
Hello I'm a title
</h3>
);
const Button = () => (
<button
style={{
backgroundColor: 'tomato',
}}
onClick={() => console.log('im clicked')}>
Click me
</button>
);
const Container = (
<div>
<Title />
<Button /> {/* 컴포넌트의 첫 글자는 반드시 대문자여야 함,
만약 소문자라면 React,JSX가 HTML button 태그라고 생각하게 됨 */}
</div>
);
ReactDOM.render(Container, root);
- 바벨로 변환된 코드
"use strict";
var root = document.getElementById('root');
var Title = function Title() {
return /*#__PURE__*/React.createElement("h3", {
id: "title",
onMouseEnter: function onMouseEnter() {
return console.log('mouse enter');
}
}, "Hello I'm a title");
};
var Button = function Button() {
return /*#__PURE__*/React.createElement("button", {
style: {
backgroundColor: 'tomato'
},
onClick: function onClick() {
return console.log('im clicked');
}
}, "Click me");
};
var Container = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Title, null), /*#__PURE__*/React.createElement(Button, null));
ReactDOM.render(Container, root);
3. 바벨로 변환 된 결과 비교
4. 결론
- 회사 프론트 개발자님에게 여쭤본 뒤 얻은 답변
- 1번 코드는 객체에 담겨진게 리턴되는 것이라 렌더할 때 태그로 감싸줘야 한다.
- 2번 코드는 () 소괄호 안에 있는 value 값을 return 한다는 의미여서 결국 리턴하는 값이 1번 코드와 같은 것
- 또한 2번 코드는 html 요소를 바로 꽂아주는 것 (???네??????)
- 결과 값이 같으니 두 방식 모두 나중에 사용하게 된다. 그러나 명확한 차이를 말해주긴 애매한 심정이다.
- Container를 콘솔에 찍어본 후 얻은 결과
- 더 모르겠음. 참조 에러가 왜 발생하는지도 잘 모르겠다. ES6 공부가 더 선행되어야 할 필요성을 느낌
React와 JSX 코드에 주석 삽입 하는 법
React, JSX 내에서 주석을 삽입하고 싶으면 아래와 같이 작성해야 문법에러가 발생하지 않음 ❌
- React 코드 주석 : 자바스크립트와 동일
/* 여러 줄의
주석 */
console.log(`Hello, ${name}!`);
- React JSX 코드 주석 : //, /* 주석을 {} (중괄호)로 감싸기
<div>
{/* 여러 줄의
주석 */}
Hello, {name}!
</div>
728x90
'TIL > React' 카테고리의 다른 글
state는 또 뭐야 (0) | 2022.04.22 |
---|---|
리액트 개발 환경과 JSX 문법 (0) | 2022.04.22 |