[TIL] React Documents Step01

Keunyeong Lee·2022년 10월 19일
0

[TIL]

목록 보기
11/15
post-thumbnail

React

Documents

Step01

1. Hello World

  • 화면에 Hello, world 표시하기
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);

html root라는 ID를 갖는 Element를 react Dom 이 렌더링할 root로 변수 선언!

그리고 root에 render!

2. JSX 소개

const element = <h1>Hello, world!</h1>;
  • html를 js 문법을 활용하여 정의하고 render 하는 문법
  • js 로 elements 를 생성하자!
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
  • 중괄호 안에서 js 문법을 활용 할 수 있다.
  • 렌더링 전에 모든 변수와 함수가 실행, 입력되고 렌더링 된다.

3. 엘리먼트 렌더링

<div id="root"></div>
  • html에 Render할 위치를 잡는다.
const root = ReactDOM.createRoot(
  document.getElementById('root')
);
const element = <h1>Hello, world</h1>;
root.render(element);
  • reactDom 이 render하기 위해 잡은 위치에 render!!
const root = ReactDOM.createRoot(
  document.getElementById('root')
);

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  root.render(element);
}

setInterval(tick, 1000);
  • render를 1초마다 하도록 하였다.
  • 이때 element 전체를 render 하도록 하였지만 reactDOM 은 전체를 render하지 않는다.
  • dom은 reder된 부분과 render할 부분을 비교하여 변경된 부분만을 다시 render 해준다.
  • 어마어마한 효율성!

4. Component와 Props

  • Component는 class component & function component 가 있다.
  • 둘 다 알고 쓰자
  • 우선 최근에 주력으로 사용되는 function component!
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;
root.render(element);
  • 함수로 정의하고 return element! => function component 생성
  • 함수 명을 element 요소 처럼 사용!
  • 심플!
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
  • function component 를 class component로 표현하면 위와 같다.
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}
  • component 안에 component로 구성
  • component 를 여러개 만들어 블럭처럼 쌓아서 만들자!!
  • 잘 만든 component는 많은 곳에 여러번 활용할 수 있다.
  • 유지 보수에 탁월!!! 멋져..
function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}
  • 마구 싸여있는 elements 들을 component로 뜯어보자!!

  • 처음부터 하나씩 구성하여 합칠 수도 있지만 만들어 놓고 뜯어가며 만드는 방식도 훌륭!

  • props 는 전달하여 읽기만 하자.( 일방 통행 )

profile
🏃🏽 동적인 개발자

0개의 댓글