리액트 기초 : 컴포넌트와 Props

웹에서 재사용이 가능한 요소를 컴포넌트라고 합니다.
이런 컴포넌틑 모아 기능을 만들고 또는 기능에서 재사용에 가능한 컴포넌트를 추출하기도 합니다.
이를 컴포넌트 합성과 추출이라고 합니다.

컴포넌트의 기본

export default function Profile() {
    return (
    <img
        src="https://i.imgur.com/MK3eW3Am.jpg"
        alt="Katherine Johnson"
    />
    )
}

이미지를 표시해주는 기본 컴포넌트 입니다.
Profile 함수는 이미지 태그를 반환합니다.

컴포넌트의 중첩

function Profile() {
    return (
        <img
            src="https://i.imgur.com/MK3eW3As.jpg"
            alt="Katherine Johnson"
        />
    );
}

export default function Gallery() {
    return (
        <section>
            <h1>Amazing scientists</h1>
            <Profile />
            <Profile />
            <Profile />
        </section>
    );
}

컴포넌트의 export와 import

App.js
import Gallery from './Gallery.js';

export default function App() {
    return (
        <Gallery />
    );
}
Gallery.js
function Profile() {
    return (
        <img
            src="https://i.imgur.com/QIrZWGIs.jpg"
            alt="Alan L. Hart"
        />
    );
}

export default function Gallery() {
    return (
        <section>
            <h1>Amazing scientists</h1>
            <Profile/>
            <Profile/>
            <Profile/>
        </section>
    );
}

gallery 컴포넌트를 export 했고, app.js에서 gallery 컴포넌트를 import 했습니다.

props 전달

import {getImageUrl} from './utils.js';

function Avatar({person, size}) {
    return (
        <img
            className="avatar"
            src={getImageUrl(person)}
            alt={person.name}
            width={size}
            height={size}
        />
    );
}

export default function Profile() {
    return (
        <div>
            <Avatar
                size={100}
                person={{
                    name: 'Katsuko Saruhashi',
                    imageId: 'YfeOqp2'
                }}
            />
            <Avatar
                size={80}
                person={{
                    name: 'Aklilu Lemma',
                    imageId: 'OKS67lh'
                }}
            />
            <Avatar
                size={50}
                person={{
                    name: 'Lin Lanying',
                    imageId: '1bX5QH6'
                }}
            />
        </div>
    );
}