[React] 기본 format과 JSX
2021. 4. 14. 23:25ㆍProgramming/WEB
How React Works
- 만들어진 React 프로젝트의 public/index.html을 확인해보면 body 가 비어있는 것을 확인할 수 있다.
index.html
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
- 그렇다면 화면에 표시되는 많은 정보들은 어디에 있는 것일까?
- React는 element들을 javascript로 만들어서 빈 html 파일 안에 밀어넣는다.
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<App/>,
document.getElementById("root")
);
reportWebVitals();
- ReactDOM은 render라는 function을 통해 root에 <App/> 을 밀어넣는다고 볼 수 있다.
- 실제로 npm start를 통해 화면을 띄워 봤을때 브라우저 화면에는 react가 랜더링한 컴포넌트들이 보이지만 소스코드를 확인했을때는 비어있다. → Virtual DOM
- <App/> 은 Component 이다. Component는 HTML을 반환하는 함수다.
App.js
import React from 'react';
function App(){
return(
<div className="App"> <h1>Hello!</h1> </div>
);
}
export default App;
- <App/> 이라고 써있는 이것은 html 문법처럼 보이는데 Component를 표기한 것이다. 이 방식은 JSX라 하며 JavaScript를 확장한 React만의 문법이다. 기본적으로 js의 모든 문법을 지원한다.
- 우리가 html css js를 사용해 웹 페이지를 만들 때, javascript code와 html(마크업)은 별도의 파일에 분리되어 작성된다. 하지만 JSX는 둘을 섞어놓은 Component 라는 유닛을 사용한다.
- 만든 component를 다른 파일에서 사용할 수 있게 하려면 export default <component name>; 을 마지막에 입력한다.
javascript 표현식
- JSX의 중괄호{ } 안에는 모든 javascript 표현식이 사용될 수 있다.
const name = 'june';
const element = <h1>Hello, {name}</h1>;
<img src={logo} className="App-logo" alt="logo" />
이렇게 tag 안에 간단하게 배치할 수 있다.
따라서 동적인 웹페이지를 만들기 좋다.
*참고
- JSX는 HTML보다는 javascript에 가깝기 때문에 React DOM은 Html의 Attribute 이름 대신 camelCase 프로퍼티 명명 규칙을 사용한다.
- class -> className
- tag 안에 다른 tag를 포함할 수도 있다.
'Programming > WEB' 카테고리의 다른 글
| node.js 프로세스 관리 도구 PM2 (--watch 옵션 trouble shooting) (0) | 2021.10.28 |
|---|---|
| React Developer Tool (0) | 2021.04.22 |
| [React] React 시작하기 (0) | 2021.04.04 |
| [Web] DOM / BOM (0) | 2021.03.01 |
| [번역] 왜 Library들이 Framework 보다 더 나은가 (0) | 2021.02.24 |