본문 바로가기
Front-end/React

React 시작하기

by softserve 2022. 9. 20.
반응형

react는 프론트엔드 개발을 위해 페이스북에서 만든 js 라이브러리입니다.

리액트의 장점은 빠르다는 것입니다. DOM을 직접 조작하지 않고 가상 DOM을 사용하며, 하나의 동적인 페이지로 구현되는 Single page application(SPA)이기 때문이죠. vue나 angular도 유사한 특성을 가지고 있습니다. 또 확장성과 재사용성, 높은 생산성과 더불어 커뮤니티의 활성화로 관련 자료를 많이 찾아볼 수 있다는 점도 리액트가 인기를 끄는 이유라고 할 수 있겠습니다.

그럼 지금부터 10초만에 리액트 프로젝트를 만드는 법을 알려드리겠습니다.

 

 

0. 준비단계 - node.js 설치하기

 

react를 설치하기 위해서는 node.js가 필요합니다.

리눅스 환경에서는 커맨드 한 줄이면 nodejs 를 설치할 수 있지만

windows에서는 installer를 다운받아 설치를 해야 하므로 조금 번거롭습니다.

1.

https://nodejs.org/ko/download/

 

다운로드 | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

여러 개의 Node.js 버전을 사용하고자 한다면, nvm을 설치하면 됩니다.

2.

https://github.com/coreybutler/nvm-windows/releases

 

Releases · coreybutler/nvm-windows

A node.js version management utility for Windows. Ironically written in Go. - coreybutler/nvm-windows

github.com

위 링크에서 설치 파일을 다운받아 nvm-windows를 설치해줍니다.

설치가 완료되었으면

windows powershell 또는 vscode의 terminal에서 

> nvm -v // nvm 설치가 제대로 되었는지 확인
> nvm install 14.0.0 // node.js 14 버전 설치. 14버전 이상을 설치해야합니다!
> nvm ls // 설치된 node.js 리스트를 확인할 수 있다.
> nvm use 14.0.0 // 14 버전을 사용
> nvm ls // 사용중인 node.js 버전에 *이 표시된다.
> node -v // node.js 버전 확인
> npm -v // npm은 node.js와 함께 설치되는 package manager이다.

 

1. 리액트 프로젝트 생성하기.

 

이제 본격적으로 리액트 프로젝트를 만들기 위한 환경세팅을 시작합니다.

> npx create-react-app my-app

자 이제 리액트 프로젝트가 성공적으로 생성되었습니다.

create-react-app 이라는 프로그램을 이용해서 my-app이라는 이름의 react 프로젝트를 만듭니다.

npx는 npm에 포함된 패키지 실행도구라고 알고 계시면 됩니다.

그럼 우리가 방금 만든 react 페이지를 웹사이트에 띄워보도록 하겠습니다.

방금 생성한 my-app 폴더에서 npm start 엔터를 누르면 끝입니다.

> cd my-app
> npm start

위와 같은 화면이 나타나면 성공입니다.

 

2. 구조 소개

 

시작이 반이라는 말이 있죠. 여러분은 벌써 리액트 학습을 절반이나 끝낸 셈입니다.

리액트 프로젝트의 구조를 간단히 살펴보면서 이번 포스트를 마치도록 하겠습니다.

my-app 폴더 안에는

public 과 src 폴더가 있습니다.

① public에는 렌더링된 결과가 표시되는 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>

상세한 설명은 주석을 참고하시고, 눈여겨 볼 것은 <div id="root"> 이 녀석입니다.

 

② src에는 js, css 등 주요 파일들이 모두 들어갑니다.

index.js가 가장 메인이 되는 파일이라고 볼 수 있고, 쓸데없는 부분을 제거하면 다음과 같습니다.

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


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

위 index.html의 root 요소에 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 는 로고 이미지와 문장 한 줄, 링크 하나로 이루어져 있습니다.

그 결과 위 사진에 보이는 것처럼 react 로고 화면이 나타나게 됩니다.

 

더 궁금한 점이 있으시면 react 공식 홈페이지를 참조하세요!

https://ko.reactjs.org/docs/create-a-new-react-app.html

 

반응형

'Front-end > React' 카테고리의 다른 글

React에서 폼 form을 다루는 방법  (0) 2023.05.25

댓글