Language/React.js

[React] React의 개요

마탁이 2021. 1. 23. 17:13

www.w3schools.com/react/

- 위 웹사이트에서 예제를 참고하며 실습한다.

 

React Tutorial

React Tutorial React is a JavaScript library for building user interfaces. React is used to build single page applications. React allows us to create reusable UI components. Start learning React now » Learning by Examples Our "Show React" tool makes it ea

www.w3schools.com

 

ko.reactjs.org/tutorial/tutorial.html

- 또한 아래 사이트에서는 이미 Game 만들기를 진행해보았고 같이 실습해보면 좋다.

 

자습서: React 시작하기 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

1. React 소개

 - React는 사용자 인터페이스를 구축하기 위한 선언적이고 효율적이며 유연한 JavaScript 라이브러리.

 - '컴포넌트' 라고 불리는 작고 고립된 코드의 파편을 이용하여 복잡한 UI를 구성하도록 돕는다.

 - 데이터가 변경될 때 React는 컴포넌트를 효율적으로 업데이트하고 다시 렌더링 한다.

 - 다수의 React 개발자는 'JSX' 라는 특수한 문법을 사용하여 React의 구조를 보다 쉽게 작성한다.

 

 

2. React 컴포넌트 클래스 예제

 - 아래는 React 컴포넌트 클래스(타입)의 예제이다.

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="shopping-list">
        <h1>Shopping List for {this.props.name}</h1>
        <ul>
          <li>Instagram</li>
          <li>WhatsApp</li>
          <li>Oculus</li>
        </ul>
      </div>
    );
  }
}

 - render 함수는 화면에서 보고자 하는 내용을 반환한다.

   React는 설명을 전달받고 결과를 표시한다.

   특히 render는 렌더링할 내용을 경량화한 React 엘리먼트를 반환한다.

 - <div /> 구문은 빌드하는 시점에서 React.createElement('div')로 변환한다.

   위의 예제는 아래와 같이 변환된다.

return React.createElement('div', {className: 'shopping-list'},
  React.createElement('h1', /* ... h1 children ... */),
  React.createElement('ul', /* ... ul children ... */)
);

 - ShoppingList 컴포넌트는 <div />와 <li /> 같은 내각 DOM 컴포넌트만을 렌더링하지만

   컴포넌트를 조합하여 커스텀 React 컴포넌트를 렌더링하는 것도 가능하다.

   예를 들어 <ShoppingList />를 작성하여 모든 쇼핑 목록을 참조할 수 있다.

 

3. React 시작하는 방법

 - React를 가장 빠르게 시작하는 방법은 HTML 파일에 직접 React script를 추가해주는 것.

<!DOCTYPE html>
<html>
  <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  <body>
  
    <div id="mydiv"></div>

    <script type="text/babel">
      class Hello extends React.Component {
        render() {
          return <h1>Hello World!</h1>
        }
      }

      ReactDOM.render(<Hello />, document.getElementById('mydiv'))
    </script>
  </body>
</html>

 - 하지만 환경 설정을 하면 더욱 깔끔한(?) React를 사용할 수 있다.

 - npm 과 node가 설치되어 있다면 'create-react-app' 명령을 이용하여 기본적인 React 앱을 생성한다.

npm install -g create-react-app
create-react-app myfirstreact

 - 성공적으로 만들어 졌다면 아래와 같은 React 기본 파일들이 생성된다.

<create-react-app>

 - power-shell과 같은 콘솔에서 위 my-react 폴더로 이동하여 'npm start'를 수행 후

   F5를 누르면 React 앱이 실행된다.

   (만약 실행되지 않는다면 launch.json에서 localhost:8080 이 아닌 localhost:3000 으로 수정한다.)

<정상적인 실행을 확인한 모습>

 - 하지만 이런 화면이 아닌 'Hello World' 부터 시작하고자 한다.

 - src 폴더내에 있는 App.js 파일을 아래와 같이 수정한다.

function App() {
  return (
    <div className="App">
      <h1>Hello World !</h1>
    </div>
  );
}

export default App;

 - 이제 실제적인 기초부터 진행하기 위해 폴더와 코드를 아래와 같이 수정한다.

<수정한 React 작업 영역 내 폴더>

- index.html 생성

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>React App</title>
    </head>

    <body>
        <div id="root">
            
        </div>
    </body>

</html>

 - index.js 수정

import React from 'react';
import ReactDOM from 'react-dom';

const myfirstelement = <h1>Hello React!</h1>

ReactDOM.render(
  myfirstelement,
  document.getElementById('root')
);