React Udemy #15: Creating a Reusable Table๐Ÿ˜ˆ

JEUNGBIN HANยท2023๋…„ 1์›” 5์ผ

React-Udemy-Lecture

๋ชฉ๋ก ๋ณด๊ธฐ
8/12
post-thumbnail

Creating a Reusable Table

  1. Make a Table Component
  2. Make a 'TablePage' component
  3. Add route to App.js to show TablePage when a user goes to '/table'
        <Route path="/table">
          <TablePage />
        </Route>
  1. Add a link to the Sildebar Component
export default function Sidebar() {
  const links = [
  //...
    { label: "Table", path: "/table" },
  ];

Communicate data to table

Parent (component)

  const data = [
    { name: "Orange", color: "bg-orange-500", score: 5 },
    { name: "Apple", color: "bg-red-500", score: 5 },
    { name: "Banana", color: "bg-yellow-500", score: 5 },
    { name: "Lime", color: "bg-green-500", score: 5 },
  ];

=>(props : fruits)
=>
Table (component)

Inside TablePage , make an data array. Use that data array as props.


function TablePage() {
  const data = [
    { name: "Orange", color: "bg-orange-500", score: 5 },
    { name: "Apple", color: "bg-red-500", score: 5 },
    { name: "Banana", color: "bg-yellow-500", score: 5 },
    { name: "Lime", color: "bg-green-500", score: 5 },
  ];
  return (
    <div>
      <Table data={data} />
    </div>
  );
}

Inside Table, Use that data as props.

export default function Table({ data }) {
  return <div>{data.length}</div>;
}

MAKE Reusable Table Component

์–ด๋–ค data๋ฅผ table์— ๋‹ด์•„๋„ ๊ทธ ์ •๋ณด๊ฐ€ ๋ณด์ด๊ฒŒ table ์„ ์žฌ์‚ฌ์šฉ ํ• ์ˆ˜ ์žˆ์–ด์•ผํ•œ๋‹ค.

Table Header

Inside 'TablePage'

  const config = [{ label: "Name" }, { label: "Color" }, { label: "Score" }];
  return (
    <div>
      <Table data={data} config={config} />
    </div>
  );

Inside 'Table'

function Table({data, config}){
  const renderedHeaders = config.map((column)=>{
    return <th>{column.label}</th>
  })
}

return (
  <thead>
    <tr>{renderedHeaders}</tr>
  </thead>  
)

Fixed Cell Values

Inside 'TablePage'

const config =
  [ 
    {label:'Name',
     render:(fruit)=> fruit.name
    }, 
    {
     label:'Color',
     render:(fruit) => <div className={`p-3 m-2 ${fruit.color}`}></div>
    }
  ]

Inside 'Table'

const renderedRows = data.map((fruit)) =>{
  return(
    <tr>
      <td>{config[0].render(fruit)}<td>
      <td>{config[1].render(fruit)}<td>
      <td>{config[2].render(fruit)}<td>
    </tr>
  )
}

Nested Maps

Inside 'Table'

const renderedRows  = data.map((fruit)=>{
  const renderedCells = config.map((config)=>{
    return (
      <td>{config.render(fruit)}<td>
    )
  })
  
  return (
    <tr>{renderedCells}</tr>
  )
})

Adding a Key function

Inside 'TablePage'

const ketFn = (fruit) =>{
  return fruit.name
}

  return (
    <Table keyFn={keyFn] /> 
  )

Inside 'Table'

return (
  <tr key={keyFn}></tr>
)
profile
Web Developer

0๊ฐœ์˜ ๋Œ“๊ธ€