본문 바로가기
  • 기록
React/(Udemy)React-The Complete Guide

[React] 리액트 기초 컴포넌트(섹션3-1)

by juserh 2022. 4. 14.

React makes building complex, interactive and reactive user interfaces simpler.

 

1. 컴포넌트(Component)

React is all about "Components".
Because all user interfaces in the end are made up of components.

: Reusable buildingblocks in user interface. Just Combination of HTML code, CSS code, JS code.

 

Why Components?

  • Reusability: 재사용성
  • Seperation of Concerns: 우려 분리 -> 작은 단위로 관리

 


2. 선언형 접근방식(Declarative Approach)

리액트는 컴포넌트를 빌드하기 위해 declarative approach를 사용한다. desired end state or target state를 정의하는 것이 중요하다. 

state state state!!!

 

https://en.wikipedia.org/wiki/Declarative_programming

 

Declarative programming - Wikipedia

Programming paradigm based on modeling the logic of a computation In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation witho

en.wikipedia.org

 


3. 리액트 기본

https://create-react-app.dev/

 

Create React App

Set up a modern web app by running one command.

create-react-app.dev

 

주요 폴더

리액트 프로젝트를 생성하면 위와 같은 폴더 구조를 가지게 된다. 참고로 위는 기본 설치 파일들 중 몇 가지를 정리한 상태이다. 주로 사용하게 될 폴더는 src폴더이다.

 

1. index.js: npm start로 페이지(localhost:3000)를 로드할 때 가장 처음 실행되는 코드 파일. 변환?

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

ReactDOM.render(<App />, document.getElementById("root"));

이 파일의 내용을 보면 react-dom을 import하여 render메소드로 렌더링하고 있다.

render메소드의 두번째 매개변수는 DOM API로 global document의 object이다.

public/index.html파일은 브라우저에 로드되는 단 하나의 html파일이다(리액트는 single page application, SPA 이기 때문에!). 이 index.html파일에 내용을 살펴보면 body부분에 root라는 id를 가진 <div>태그(<nonscript>태그를 제외하면 body부분의 유일한 html요소로 존재)가 있는 것을 볼 수 있다.

위 index.js파일의 render메소드의 두번째 인자로 주어진 document.getElementById("root")가 바로 이 <div>태그를 가져온다. 그리고 이 <div>태그의 컨텐츠로 render메소드의 첫번째 인자로 주어진 <App/>을 넣어주는 것이 위 index.js에서 하는 일이다. <App />은 jsx syntax로, 컴포넌트라고 할 수 있다.

 

2. App.js

function App() {
  return (
    <div className="App">
      <h1>Let's get started!</h1>
    </div>
  );
}

export default App;

App function을 export하고 있다(여기서 export한 App을 index.js파일에서 import함). 코드를 전체적으로 보면 자바스크립트 코드이지만 그 안에 html코드를 return하는데. 이는 JSX syntax로 html구문에 대해서 변환작업이 이루어져서 가능한 것이다.

 


4. JSX

자바스크립트 안에 있는 html코드를 말하는데, JSX는 JavaScript XML의 약자이다.

리액트는 jsx syntax로 작성할 수 있지만, jsx는 브라우저에 지원되지 않아 리액트가 이를 자동으로 변환해주어 브라우저에 나타나는 것이다.

개발자도구를 열어 소스코드, 그 중에서도 자바스크립트 코드를 살펴보면 App() function을 발견할 수 있는데 그 내용을 살펴보면 우리가 앞서 작성했던 코드와 다른 것을 알 수 있다. 리액트에서 변환한 코드가 보여지는 것이다.

 


5. 리액트 작동 방식

표시한 부분이 우리가 브라우저에 나타나길 원하는 target state이다. App은 custom eliment라고 할 수 있다.

리액트는 jsx syntax로 html코드로 간단하게 새로운 html요소를 생성할 수 있다.

 

그냥 자바스크립트로 html요소를 생성하는 것과 비교하면 다음과 같다.

fuction App(){
    const para=document.createElement('p');
    para.textContent='This is also visible';
    document.getElementById('root').append(para);
    
    return (
    	<div>
            <p>This is also visible</p>
        <div>
    );
}
export default App;

자바스크립트는 imperative approach(명령형 접근 방식)을 따르고 있기 때문에 단계별로 생성을 지시해야 한다. 반면 리액트는 앞에서도 언급했듯이 declarative approach(선언형 접근 방식)으로 최종상태를 정의하기만 하면 된다.