1

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>
2
  • 1
    the key can be anything, even hard coded if it's important to get rid of the warning (<th key="1">Col1</th>). If you have data you're iterating over it can be the id, the name, or whatever. Or if you really want to go all out you can generate a uuid for each item. Commented Nov 9, 2021 at 23:02
  • 1
    if histories have an id, you could do <tr key={h.id}>, that's most likely where the warning is coming from Commented Nov 9, 2021 at 23:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. The part that I didn't know is that it needed to be part of the <tr>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.