Home > Back-end >  How to specify keys in React Bootstrap table
How to specify keys in React Bootstrap table

Time:11-10

Using React Bootstrap table, I'm getting the warning Warning: Each child in a list should have a unique "key" prop. I've read about how this is necessary for lists, but not sure where I'm supposed to set a key for a Table? My table looks something like this

 <Table size="sm" responsive="sm" bordered hover striped>
                <thead>
                <tr>
                    <th>Col1</th>
                    <th>Col2</th>
                    <th>Col3</th>
                    <th>Col4</th>
                </tr>
                </thead>
                <tbody>
                { histories.map((h) => (
                    <tr>
                        <th>{ h.col1} </th>
                        <th> { h.col2}</th>
                        <th> { h.col3}</th>
                        <th>{ h.col4}</th>
                    </tr>
                )) }
                </tbody>
            </Table>

CodePudding user response:

This would work is there's an id for histories.

{ histories.map((h) => (
  <tr key={h.id}>
    <th>{ h.col1} </th>
    <th> { h.col2}</th>
    <th> { h.col3}</th>
    <th>{ h.col4}</th>
  </tr>
)) }

The key can really be anything (even h.col1 if you like), as long as it's unique within that list. It's not super important to have (hence the warning instead of error), but it's definitely is good practice when you're iterating over some data and rendering a list from it, in order to prevent some unpredictable behavior, and to help React do its thing properly.

CodePudding user response:

You can pass key like:

{ histories.map((h, key) => (
  <tr key={key}>
  </tr>
)) }
  • Related