React.js - component, props

김민경·2023년 1월 26일
0

FE(WEB) - React

목록 보기
3/13

React makes building complex, interactive and reactive user interfaces simpler

React is all about "Components"

Because all user interfaces in the end are made up of components

What is Component?

일반적으로 표시되어야 하는 HTML(JSX) 코드를 반환하는 javascript 함수

Why Components?

  • Reusability(재사용성)
    - don't repeat yourself
  • Seperation of Concerns(관심사의 분리)
    - don't do many things in one and the same place(function)
    => split big chunks of code into multiple smaller functions

How is a component built?

=> by declarative approach(선언적 접근방식)
= define the desired target state(s) and let React figure out the actual JS DOM instructions

*declarative approach(선언적 접근방식) vs imperative approach(명령형 접근방식)

  • (imperative appraoch)
    순수 js 코드의 경우
    document.createElement()
    document.getElementById()
    등을 통해 직접 일일이 HTML DOM에 접근해야 한다
  • (declarative approach)
    JSX 코드를 이용하면
    return문에 HTML 코드를 직접 작성함으로서
    보다 편리하게 코드를 짤 수 있다

=> build your own, custom HTML elements

Building a component tree

(DOM 노드에 마운트되는 하나의 루트 컴포넌트를 가진 컴포넌트 트리)

component는 어떻게 분할해야 할까?
=> 최대한 단일 기능만 수행하는 반복적인 코드들로 분할하는 것이 좋다!

Creating a react app

(node.js가 깔린 상태여야 한다!)

원하는 폴더에 가서
npx create-react-app 프로젝트명
cd 프로젝트명
npm start

기본적인 폴더 구조

public

  • index.html
<div id="root"></div>

src

  • index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
  • App.js : a root component
function App () {
	// js 코드들   
    return()
}

const App = () => { 
	// js 코드들
	return() 
}
  • components 폴더 : 각종 components를 담을 수 있는 폴더

JSX란?

: react가 제공하는 특수 편의 문법(syntatic sugar)(html, js, css를 혼용해서 쓸 수 있다!)

=> 브라우저에서는 리액트 라이브러리(import React from 'react')를 이용해
js문법으로 변환해 쓴다!
(F12개발자 도구 -> Sources -> page에서 확인할 수 있다)

*import React from 'react'
과거 버전에는 모든 파일에 일일이 불러와줘야 됬었지만
현재 버전에서는 일일이 불러와줄 필요는 없다!
정통 방식:

React.createElement(태그명, {속성명 : 속성 값}, 내용)

JSX 문법

  • return문에
<>다른 div들...</> 
또는 
<div>다른 div들...</div>

로 전체를 감싸줘야 한다!

*만약 custom component를 코드 전체를 감싸는 태그로 이용하고 싶다면...
(ex. Card.js)

const Card = (props) => {
  const classes = 'card ' + props.className;
  return <div className={classes}>{props.children}</div>;
};

div 태그를 리턴하고 props.children을 내용으로 담고 있는 구조

-class명은 className으로!
-React 컴포넌트 내부의 동적 데이터(반환된 JSX 코드)는 {}로!

  • props로 전달하기

component에서 하위 component로 무언가를 전달하고 싶을 때 props를 쓴다
(객체 형태로 전달이 된다) (상위->하위)

profile
🏛️❄💻😻🏠

0개의 댓글