개발/React

React - React.js 기초 (설치 및 실행)

잇(IT) 2023. 9. 14. 20:46
728x90
- React.js

1. 반복적인 코드를 줄 일 수 있다.  

- 컴포넌트와 방식을 사용하기 때문에 중복된 코드로 인한 산탄총 수술을 할 필요가 없어진다.

- 즉, React는 Component 기반의 UI 라이브러리이다.

2. 선언형 프로그래밍으로 목적을 바로 나타낸다.

- 프로그래밍 방식에는 명령형 프로그래밍 (대표적으로 jQuery)가 있고, 선언형 프로그래밍에는 (React)가 있다.

- 선언형 플로그래밍은 목적을 바로 나타내기 때문에 코드의 목적이 간결하고 확실해진다.

3. V

irtual DOM

- DOM (Document Object Model)은 태그, 아이템이 코드에 추가 될 때마다 브라우저가 웹 페이지를 보여주기 위해 동작하는 흐름이 계속해서 반복적으로 일어난다.

- React는 Virtual DOM을 사용하여 변화를 실시간으로 업데이트 하는 것이 아닌 가상의 DOM에 변경 사항을 저장한 다음 한 번에 실제 DOM을 업데이트 하는 방식을 사용한다.


- Create React App

- VSC 터미널

npm -v
node -v
npx -v

// npx -v가 출력되지 않는다면 npm install -g npx를 통해 설치

 

- React App 설치
npx create-react-app [디렉토리명]

- create-react-app 명령어를 통해 react app을 설치한다.

- 설치하게 되면 위와 같이 파일들이 생성된다.

 

npm start

- 터미널에 npm start 명령어를 입력하면 scripts에 의해

- 위와 같이 react app이 실행된다.

- react app을 생성하게 되면 위와 같이 여러 파일들이 생성되는데

 

- App.js

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

- App.js 파일을 보면 화면을 구성하는 코드들이 있는 것을 확인 할 수 있다.

- 하지만 위 파일은 html 파일이 아니며 html 구성을 취하고 있지도 않다.

- 또한 개발자 도구를 통해 코드를 보게 되면 root 아래 App 클래스가 있는 것을 확인 할 수 있다.

 

- index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

- 대부분의 애플리케이션의 기본 파일이 되는 index.js 파일을 보게 되면 ReactDOM.createRoot(document.getElementById('root'))를 통해 id가 root인 엘리먼트를 찾아 React 애플리케이션의 루트(root)로 지정한다.

- root.render를 통해 root가 root 엘리먼트인 React 애플리케이션을 렌더한다.

- root.render(<App />);

root.render(
    <App />
);

- 위의 코드는 아래 설명하겠지만 간단히 말하자면 App의 컴포넌트를 가져오는 코드이며 엘리면트가 root인 곳에 포함시킨다.

- 그렇다면 root 엘리먼트는 어디에 있는지 찾아보게 되면

 

- index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <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>
</html>

- React 애플리케이션을 생성하면서 생긴 index.html 파일 안에 <div id="root"></div> 를 찾을 수 있고 위에서 우리가 설정한 root 엘리먼트에 해당한다.

- 해당 엘리면트 안에 <App /> 컴포넌트가 추가되어 최초에 봤던 페이지를 우리가 볼 수 있게 되는 것이다.

728x90