VanillaJS를 React 같이 코딩하기 - 시작하기

bepyan·2021년 4월 18일
2
post-thumbnail

🍌 프로젝트 구조

디랙토리설명
index.html브라우저에 옵로드될 HTML파일
apifetch 관련 유틸리티
assertsgif, png와 같은 이미지 정적 파일
componentsUI를 출력하는 컴포넌트 ( prop의 함수에 의해 state를 변경 )
container데이터와 데이터 조작에 관한 함수를 components를 제공
stylescss 파일
App.jsApp 컴포넌트
index.js애플리케이션의 시작점 (App을 생성)
  • Presentational & container Pattern 이다.
  • 반드시 지켜야할 규칙이 아니니 상황과 본인 취향 것 적용하면 된다.

index.html

<!DOCTYPE html>
<html>

<head>    
    <meta charset="utf-8" />
    <title>PYAN-BOARD</title>
    <link rel="stylesheet" href="../src/styles/index.css"/>
</head>

<body>
    <main class="app"></main>
    
    <script src="../src/index.js" type="module"></script>
</body>

</html>

index.js

import App from './App.js'
new App(document.querySelector('.app'))

html파일에 있는 <main class="app"></main>에 애플리케이션을 시작한다.

App.js

import Board from "./container/Board.js"

export default function App($app) {
    this.state = {
        
    }
    /* Render Children*/
    const board = new Board({ $app, initialState: this.state })
}

Board.js

export default function Board({ $app, initialState }) {
  
    this.$target = document.createElement('div');
    $app.appendChild(this.$target);
    this.state = initialState;
  
    this.setState = (nextState) => {
        this.state = nextState;
        this.render();
    }
    // init EventListener
    
    // this.state 바탕으로 랜더링
    const render = () => {
        this.$target.innerHTML = `
            <h1>Board List</h1>
     	`
    }
    render();
}
  • 기본 로직은 root element 를 가져와 UI와 관련 이벤트를 첨가한다.
  • this.render()를 통해 해당 컴포넌트를 출력한다.
  • App.js에서 board.render()하면 Board 컴포넌트가 리랜더링 된다.
  • 다음 포스트에서 이벤트 거는 동작을 살펴보자.

🚀 App 실행하기

  1. Live Server 설치
  2. 하단에 Go Live 클릭
  3. index.html 파일이 있는 디랙토리로 이동하면 된다.

🔎 유용한 vscode 플러그인

  • innerHTML Syntax Highlighting
this.$target.innerHTML = `
  <form>
    <input placeholder="ID">
    <button type="submit">submit</button>
  </form>
`
`` 내부의 html 문법을 체크해준다.
profile
쿠키 공장 이전 중 🚛 쿠키 나누는 것을 좋아해요.

0개의 댓글