React day2

1. 설치

설치할 항목

Nodejs : 리액트 프로젝트를 준비하기 위해 필요한 webpack, babel 등의 도구들을 실행하는데에 사용됩니다.

Yarn : 자바스크립트 패키지를 관리하기 위해서 사용됩니다.

Node.js 를 설치하면 npm 이 설치되어서 npm 으로 해도 되긴 하지만,

yarn을 사용하면 훨씬 빠릅니다.

=> Nodejs

https://nodejs.org/ko/ => LTS 버전

=> Yarn

https://classic.yarnpkg.com/en/docs/install#windows-stable

npm install --global yarn

재부팅

=> VS Code ( 에디터 )

https://code.visualstudio.com/에 들어가셔서 설치하세요

vs code 확장설치

Live Server

Reactjs code snippets

Korean Language Pack for Visual Studio Code

Auto Close Tag

Auto Complete Tag

Auto Import

Auto Rename Tag

2. React 프로젝트 생성

https://create-react-app.dev/docs/getting-started

Getting Started | Create React App
Create React App is an officially supported way to create single-page React

create-react-app.dev

npx create-react-app 프로젝트명

cd 프로젝트명

npm start or yarn start - 실행

==============================

yarn create react-app 프로젝트명

==============================

3. cd 프로젝트명

4. yarn start


JSX: JavaScript + XML
(Tag처럼 쓸 수 있으나, Tag는 아니고 JavaScript 객체)
(얼핏 보면 HTML 같지만, 실제로는 JavaScript..JSX 문법에는 if나 for를 사용할 수 없음)

function App() {
        return (
        <div>
        // 이 안에 JSX가 들어간다
        </div>
        )
    }

React는 실제 돔이 아닌 가상 돔을 사용 (속도)

node_modules 폴더: 의존성 (이 안에 react 폴더가 있음)

public 폴더 안에 index.html 안에 root가 실제 돔에 해당
src 안에 실제 프로젝트 작업 index.js 안에

package.json: 지금 쓰고 있는 것들 확인 가능
(react, react-dom, react-scripts, web-vitals...)


index.js 분석
import React from 'react'; (node_modules 안에서 지원해주는 의존성을 가지고 오는 것이기 때문에 ./를 쓰지 않아도 됨)
import App form './App'


단축키
Reactjs code snippets 설치한 경우에 사용 가능한 단축키

rcc
rsc


  1. class component

    import React, { Component } from 'react';
    class Component_name extends Component {
        render() {
            return (
                // JSX
            (
        }
    }
  2. function component

    function App() {
            return (
            <div>
            // JSX
            </div>
            )
        }
        

규칙

  1. 태그는 반드시 닫는다
  2. 최상단에서는 반드시 div로 감싸준다

rcc: class 만들기
src: function 만들기

    import React, { Component } from 'react';
    class Component_name extends Component {
        render() {
            return (
                <h1> 1줄은 div로 감싸지 않아도 출력된다..</h1>
                <p>한 줄 이상일 경우 반드시 div로 묶어줘야 리턴된다</p>
                <p>모든 태그는 반드시 닫는 태그가 존재해야 하며</p>
                <p>빈 태그일 경우도 반드시 /로 마무리 해야 한다</p>
                <hr />
                <br />
                <input type="text" />
            (
        }
    }
    

Public 폴더 안에 index.html 만들기
Src 폴더 안에 index.js 만들기
Src 폴더 안에 components 폴더 만들어서 Test1.js...등 파일 만들기
Test1.js => rcc
App.js => rcc =>

      import React, { Component } from 'react';

      class Test2 extends Component {
        // CLASS SECTION

        render() {
          // JS SECTION
          const title = 'with JSX'
          const name = 'jean'
          const age = 20
          const address = 'bundang'
          const sex = 'f'
          const mobile = '0000'

          return (
            <div>
              {/* JSX SECTION */}
              {/* to print something in JS, we should use {} */}
              {/* comment in JSX */}
              <h1>{title} : profile</h1>
              <ul>
                <li>name: {name}</li>
                <li>age: {age}</li>
                <li>address: {address}</li>
                <li>sex: {sex}</li>
                <li>mobile: {mobile}</li>
              </ul>

              <p /*in JSX, we can comment in the tag*/>
              </p>

            </div>
          );
        }
      }

      export default Test2;
      
    ---

    import React, { Component } from 'react';

    class Test3 extends Component {
      render() {
        const txt1 = 'practicing' // React doesn't need ;
        const txt2 = 'React'

        // React prefers SASS
        const style1 = {  // css = obj type, so we use {}
          backgroundColor: 'pink',  // background-color => backgroundColor (React can't detect '-')
          border: '1px solid #000',
          width: 400,     // no need 'px'
          height: 400,
          lineHeight: '50px'
        }

        const style2 = {
          backgroundColor: 'yellow',
          border: '1px solid #000',
          width: 400,
          height: 400,
        }

        return (
          <div>
            <h1 style={style1}>txt: {txt1}</h1>
            <h1 style={style2}>txt: {txt2}</h1>
            <p style={{
              color: 'black',
              backgroundColor: 'lime',
              fontSize: 100,
            }}>css directly => double brackets</p>
            <p>hello</p>
          </div>
        );
      }
    }

    export default Test3;
    

    import React, { Component } from 'react';

    class Test5 extends Component {
      // CLASS SECTION
      render() {
        // JS SECTION
        const done1 = true
        const done2 = false
        const done3 = undefined

        return (
          <div>
            {/* JSX SECTION */}
            {/* can't use If / For in React */}
            {/*  */}

            {/* ternary operator */}
            <p>
              {
                done1 === true? <button>Sign-in</button> : <button>Sign-out</button>
              }
            </p>

            <p>
              {
                done2 === true? <button>Sign-in</button> : <button>Sign-out</button>
              }         
            </p>

            {/* && */}
            <p>
              {
                done1 && <button>Logged-in</button>
              }
            </p>

            {/* || : not used very often */}
            <p>
              {
                done3 || 'Logged-out'
              }
            </p>
          </div>
        );
      }
    }

    export default Test5;
    

Fragment, <></>: 불필요한

를 줄여준다


props / state


자바스크립트는 변수 선언 후 값을 넘겨주는 방식으로 쓰지만,
리액트는 값을 나중에 유동으로 바꾸고 싶으면 그건 다 state로 선언하고,
this.state로 나중에 값을 변경해야 한다

클래스
state = {} // 클래스형에서 값 선언
this.setState({}) // 값 변경

함수형
const [ state, setState ] = useState(초기값)

클래스 state={}

좋은 웹페이지 즐겨찾기