Create React App 실행해보기 - 1주차

2022. 6. 2. 07:55·공부하기/React

개발환경 만들기

1. Node 설치

https://nodejs.org/en/

 

Node.js

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

nodejs.org

Create React App 링크

https://github.com/facebook/create-react-app

 

GitHub - facebook/create-react-app: Set up a modern web app by running one command.

Set up a modern web app by running one command. Contribute to facebook/create-react-app development by creating an account on GitHub.

github.com

 

2. 터미널에서 실행

sudo npm Install -g create-react-app

실행 결과 1

 

3. 개발환경 세팅을 원하는 곳에 디렉토리 생성 (디렉토리명 : react-app 대문자 불가)

 

 

4. 터미널에서 디렉토리로 이동 후 create-react-app 실행

cd  디렉토리 주소

create-react-app . 

 

5. 에디터 다운로드 - 비주얼 스튜디오 코드

 

6. 비주얼 스튜디오 코드로 create-react-app 실행

npm run start 

실행 결과 2

* Command + C로 종료 


자바스크립트 파일 둘러보기 - 컴포넌트

 

index.html 파일은 실행된 앱의 진입점이다.

이 파일에서 div 태그는 "root"라는 id를 가진 태그이다.

// index.html

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

 

이 부분은 index.js 파일에서 root를 가리킨다.

// index.js

const root = ReactDOM.createRoot(document.getElementById('root'));

 

index.js 파일의 App 컴포넌트는 index.js 파일이 아닌 app.js 파일에서 구현된 컴포넌트이다.

//index.js

import App from './App';

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

 

컴포넌트 방식으로 사용하기 위해 함수 방식으로 구현된 App.js 파일의 코드를 변경한다.

extends Component를 사용하면 자동으로 react의 Component가 import된다.

// App.js

import { Component } from 'react';

class App extends Component {
  render() {
    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>
    )
  }
}

* 컴포넌트는 return문 안에 하나의 태그만 사용해야 한다.

 


배포

 

1. 빌드 폴더 생성

npm run build

 

2. 터미널에서 serve 설치

sudo npm install -g serve

 

3. 비주얼 스튜디오 코드로 serve 실행

serve -s build

실행결과 3

http://192.168.45.7:3000

외부 브라우저에서도 이 주소를 입력하면 접속할 수 있다.

 


컴포넌트화

 

순수한 html 파일로 만든 파일은 복잡해질 수 있다.

<html>
    <body>
        <header>
            <h1>WEB</h1>
            world wide web!
        </header>

        <nav>
            <ui>
                <li><a href="1.html">HTML</a></li>
                <li><a href="2.html">CSS</a></li>
                <li><a href="3.html">JavaScript</a></li>
            </ui>
        </nav>

        <article>
            <h2>HTML</h2>
            HTML is HyperText Markup Language.
        </article>
    </body>
</html>

 

각 태그 부분을 Component 클래스를 상속받은 클래스로 변경한다.

header -> Subject

nav -> TOC

article -> Content

// App.js

import './App.css';
import { Component } from 'react';


class Subject extends Component {
  render() {
    return (
      <header>
        <h1>WEB</h1>
        world wide web!
      </header>
    );
  }
}

class TOC extends Component {
  render() {
    return (
      <nav>
          <ui>
              <li><a href="1.html">HTML</a></li>
              <li><a href="2.html">CSS</a></li>
              <li><a href="3.html">JavaScript</a></li>
          </ui>
      </nav>
    );
  }
}

class Content extends Component {
  render() {
    return (
      <article>
          <h2>HTML</h2>
          HTML is HyperText Markup Language.
      </article>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div className='App'>
        <Subject></Subject>
        <TOC></TOC>
        <Content></Content>
      </div>
    );
  }
}

export default App;

실행결과 4

 

참고) App.js 파일은 순수 자바스크립트가 아닌 페이스북에서 만든 유사 자바스크립트 파일(JSX)로 create-react-app이 자동으로 변환해준다.


컴포넌트에 속성 추가해서 재사용하기 (JSX의 props)

// App.js

import './App.css';
import { Component } from 'react';


class Subject extends Component {
  render() {
    return (
      <header>
        <h1>{this.props.title}</h1>
        {this.props.sub}
      </header>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div className='App'>
        <Subject title="WEB" sub="world wide web!"></Subject>
        <Subject title="React" sub="For UI"></Subject>
      </div>
    );
  }
}

export default App;

실행결과 5


참고) 리소스 파일 새로고침하는 방법

 

 

저작자표시 비영리 변경금지 (새창열림)

'공부하기 > React' 카테고리의 다른 글

Create React App 4주차 - 클래스 & 함수 타입 컴포넌트와 라이프사이클  (4) 2022.07.14
Create React App 3주차 - Create/Update/Delete  (0) 2022.06.30
Create React App 실행해보기 - 2주차  (0) 2022.06.15
'공부하기/React' 카테고리의 다른 글
  • Create React App 4주차 - 클래스 & 함수 타입 컴포넌트와 라이프사이클
  • Create React App 3주차 - Create/Update/Delete
  • Create React App 실행해보기 - 2주차
hyunjicraft
hyunjicraft
모든 것을 기록하고 싶었지만 복잡하지 않은 것만 기록하게 된 블로그
    반응형
  • hyunjicraft
    개발망고발
    hyunjicraft
  • 전체
    오늘
    어제
    • 분류 전체보기
      • iOS
        • Swift
        • RxSwift
      • 공부하기
        • React
        • Python
        • 다른 PL
        • Figma
      • 스타트업
      • 글쓰기
        • 회고
  • 블로그 메뉴

    • 태그
  • 인기 글

  • 태그

    피그마 인스턴스
    맥에서 블렌더
    알고리즘
    블렌더
    setState()
    swift
    react
    URLSessionDataTask
    blender g
    함수방식 컴포넌트
    RxSwift 비교
    중니어
    RxSwift image download
    daummap
    ios system architecture
    생활코딩
    게임런칭
    스타트업개발
    RxSwift 이미지 다운로드
    computer systems
    Python
    비동기 프로그래밍
    swift codable
    mvvm-c
    기술적도전
    블렌더 g키
    마스터 컴포넌트 연결 해제
    Communication Patterns
    스타트업경험
    문자열 포맷
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
hyunjicraft
Create React App 실행해보기 - 1주차
상단으로

티스토리툴바