본문 바로가기
Research/React

React_props 깔끔하게 가져오기

by RIEM 2023. 4. 24.

React

객체 분해 할당으로 props 가져오기

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

import './index.css';

const books = [
  {
    author: 'Charles Dickens',
    title: 'Interesting Topics',
    img: './images/book-1.jpg',
    id: 1,
  },
  {
    author: 'Laura Dave',
    title: 'The Last Thing He Told Me',
    img: './images/book-2.jpg',
    id: 2,
  },
];

const BookList = () => {
  return (
    <section className='booklist'>
      {books.map((book) => {
        return <Book book={book} key={book.id} />;
      })}
    </section>
  );
};

const Book = ({ book: { img, title, author, children } }) => {
  return (
    <article>
      {/* Dynamically render title */}
      <img src={img} alt={title} />
      <h2>{title}</h2>
      <h4>{author}</h4>
      {children}
    </article>
  );
};

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

root.render(<BookList />);

 

spread oprator로 props 가져오기

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

import './index.css';

const books = [
  {
    author: 'Charles Dickens',
    title: 'Interesting Topics',
    img: './images/book-1.jpg',
    id: 1,
  },
  {
    author: 'Laura Dave',
    title: 'The Last Thing He Told Me',
    img: './images/book-2.jpg',
    id: 2,
  },
];

const BookList = () => {
  return (
    <section className='booklist'>
      {books.map((book) => {
        return <Book {...book} key={book.id} />;
      })}
    </section>
  );
};

const Book = (props) => {
  const { img, title, author, children } = props;
  return (
    <article>
      {/* Dynamically render title */}
      <img src={img} alt={title} />
      <h2>{title}</h2>
      <h4>{author}</h4>
      {children}
    </article>
  );
};

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

root.render(<BookList />);

댓글