Home > OS >  ReactJS add table rows
ReactJS add table rows

Time:08-25

I want an app.js that imports a component, that generates a row in a table for each element in an array.

import myRows from './myRows';
const myApp = ({ values}) => {
return (
   
    <div>
  <div>        
        {values.map((entry, index) => {
            return <myRows entry={entry} key={index}/>
        })}
    </div>
    </div>

)

} ...

const myRows = ({ entry}) => {
    return (

      **ROW ENTRY like row name = entry.name**


    )
}

...

Maybe I should create in the my App.js a table and create in the map function a row for each entry in values? Idk how to do that. I want a simple table where each row is created with each entry in values My idea is not working and mybe it is stupid and there are many better ways..

import myRows from './myRows';
const myApp = ({ values}) => {
return (
        <table>
                <thead>
                    <tr>
                        <th>1</th>
                        <th>2</th>
                        <th>3</th>
                        <th>4</th>
                        <th>5</th>
                        <th>6</th>
                        <th>7</th>
                    </tr>
                </thead>
                <tbody>
                     {values.map((entry, index) => {
            return <myRows entry={entry} key={index}/>
        })}
                </tbody>
            </table> 
       
   

)

} ...

 const myRows = ({ entry}) => {
    return (

                    <tr>
                        <th>entry.name</th>
                        <td>entry.secondName</td>
                        <td>C</td>
                        <td>D1</td>
                        <td>entry.value22</td>
                        <td>E3</td>
                        <td>E4/</td>
                    </tr>


    )
}

...

CodePudding user response:

Don't use index as key. Each entry should have a unique identifier; either an id or you can interpolate some values to create a unique key for each row (e.g key={${row.name}_${row.createdAt}}

const App = ({ array }) => {
  return <table>
    <tbody>
      { array.map(row => <Row data={row} key={row.id} />) }
    </tbody>
  </table>
}

const Row = ({ data }) => {
  return <tr>
    <td>{data.name}</td>
    <td>{data.created}</td>
    ...
  </tr>
}
  • Related