본문 바로가기
React

React : study(3) { React Component, Props, Children }

by yaans 2023. 1. 25.

React Element

리액트로 화면을 그려내는데 가장 기본적인 요소

jsx 문법을 javascript 변수에 담아 활용할 수 있다

const root = ReactDOM.createRoot(document.getElementById('root'));

const element = <h2>Dice Game</h2>;

console.log(element);
root.render(element);

 

console에 기록한 element 변수의 값을 보면

결과적으로 javascript 객체로 반환하는 것을 확인할 수 있다

 

이를 React Element라고 한다

 

 

React Component

React Element를 이용하여 커스텀 태그를 만들수도 있는데, 이를 React Component라고 한다.

본격적인 React 개발에서는 element를 Component로 만들어서 주로 사용

function Hello() {
  return <h1>react component : Custom tag</h1>
}
const component = (
  <>
    <Hello />
    <Hello />
    <Hello />
  </>
);

root.render(component);

 

 

결과 확인

 

단, React Component로 커스텀 태그를 만들기 위해서는 함수의 첫 글자를 '대문자'로 작성해야 한다

> 소문자라면 오류 발생!

 

함수 안에 필요한 컴포넌트를 구성하고 export 하면, 더욱 더 독립적으로 모듈로써 활용이 가능하다

function App() {
    return (
        <div>
            App Component 
        </div>
    );
}
export default App;     // export를 통해 이 컴포넌트를 다른 파일에서도 활용 가능

 

다른 파일에서 활용하기 위해서는 import로 정의해준 다음 사용하면 된다

import App from './App';

...

const appTag = ReactDOM.createRoot(document.getElementById('appTag'));

...

appTag.render(<App />);

 

https://github.com/KOO-YS/cramming-react/commit/d1ccde46bccb0994b2d9a3f97a0de5edac033574

 

how to use React element & component · KOO-YS/cramming-react@d1ccde4

Show file tree Showing 17 changed files with 219 additions and 2 deletions.

github.com

 

 

 


Props

JSX 문법에서 리액트 컴포넌트의 속성 (Properties)

 

속성 값을 활용하여 이미지를 바꾸는 등 다양한 변화를 줄 수 있다

[ 속성 값이 활용되는 part ] 

import diceBlue from './assets/dice-blue-1.svg';
import diceRed from './assets/dice-red-1.svg';

function Dice(props) {
    const diceImg = props.color === 'blue' ? diceBlue : diceRed; // 속성 값에 따라 다른 이미지
    return <img src={diceImg} alt='dice' />
}

export default Dice;

[ 속성 값을 선언하는 part ]

function App() {
    return (
        <div>
            ...
            <Dice color='red'/>
        </div>
    );
}

 

 

결과 확인

 

+ 활용

import diceBlue01 from './assets/dice-blue-1.svg';
import diceBlue02 ...

import diceRed01 from './assets/dice-red-1.svg';
import diceRed02 ...

// 배열 선언
const DICE_IMAGES = {
    blue : [diceBlue01, diceBlue02, diceBlue03, diceBlue04, diceBlue05],
    red : [diceRed01, diceRed02, diceRed03, diceRed04, diceRed05]
};

function MultiDice(props) {
    const src = DICE_IMAGES[props.color][props.num-1];
    const alt = `${props.color} ${props.num}`;
    return <img src={src} alt={alt} />;
}

export default MultiDice;

 

 

더보기

+ 함수의 매개변수 props 대신 구체적인 변수명을 적어서 활용해도 된다

 

function MultiDice({color = 'blue', num = 1}) {  // props 내 구체적인 속성명 사용 & 기본값 제공
    const alt = `${color} ${num}`;
    const src = DICE_IMAGES[color][num-1];
    return <img src={src} alt={alt} />;
}

 

실행 결과

https://github.com/KOO-YS/cramming-react/commit/09e502a7314572ac83622441866cce1c7b30f852

 

how to use props in React Component · KOO-YS/cramming-react@09e502a

Show file tree Showing 3 changed files with 52 additions and 3 deletions.

github.com

 

 

 


children

컴포넌트의 자식들을 값으로 받는 prop

위에서 사용해보았던 props을 활용해 버튼 내 텍스트 값을 바꿔보자

 

버튼 컴포넌트를 만들기 위한 새로운 Button.js 파일을 만들고

function Button({text}) {
    return <button>{text}</button>;
}
export default Button;

 

App.js에 버튼 컴포넌트를 추가해보았다

import Button from './Button';

...

function App() {
    return (
        <div>
        	...
            <div>
                <Button text='button text'/>
                <Button text='change text'/>
            </div>
        </div>
    );
}
export default App;

 

이런 방법을 사용하면 text의 값에 따라 버튼 내 값을 달리할 수 있다.

 

children을 활용

children을 활용하면 좀 더 직관적이고 간편하게 텍스트를 바꿀 수 있다

 

Button.js 코드의 props을 다음과 같이 고친다면

function Button({children}) {
    return <button>{children}</button>;
}
export default Button;

 

App.js의 Button 컴포넌트 태그를 좀 더 직관적으로 수정할 수 있다

 

children 값은

컴포넌트 태그를 <컴포넌트/> 형식이 아닌 <컴포넌트>children</컴포넌트>로 감싸야 되는 점을 주의

<div>
    <Button>button text</Button>
    <Button>change text</Button>
</div>

 

children은 단순 텍스트 뿐만 아니라, 다른 컴포넌트(컴포넌트 안에 컴포넌트)와 html 태그 역시 작성 가능하다 

https://github.com/KOO-YS/cramming-react/commit/f0ffdbf9c241e81f9432e24d781f8d8656825d11

 

how to use children property · KOO-YS/cramming-react@f0ffdbf

Show file tree Showing 2 changed files with 12 additions and 0 deletions.

github.com

 

 


출처 : Code it "React 웹 개발 시작하기" 강의를 보며 실습합니다.

댓글