skip to Main Content

after I fetch the array from API, I use the data to build a table using a child component:

<tbody>
    {data.map((item, index) => (
      <Row key={index} item={item} deleteMe={deleteChild}/>
    ))}
</tbody>

How can I use the above index in the Row component? The child is using the array data like this:

return (
  <tr>
    <td>**Here should be the index**</td>
    <td>{item.exerciseName}</td>
    <td>{item.instructions}</td>
  </tr>
  );

UPDATE
Thank you for all the answers, managed to show the index using your suggestions.

3

Answers


  1. The key property is used by React under the hood and is not exposed to you.
    You will have to make another prop passed on to the child and access it as you like.

    Login or Signup to reply.
  2. You can use props to do so,

    <Row key={index} item={item} deleteMe={deleteChild} index={index}/>
    

    and inside your child component you can use it by props.index

    return (
        <tr>
            <td>{props.index}</td>
            <td>{item.exerciseName}</td>
            <td>{item.instructions}</td>
        </tr>
    );
    
    Login or Signup to reply.
  3. You can pass the index as a separate prop.

    {data.map((item, index) => (
        <Row key={index} item={item} index={index} deleteMe={deleteChild}/>
    ))}
    

    Then, it can be directly accessed inside the Row component.

    function Row({item, index}) {
        return (
          <tr>
            <td>{index}</td>
            <td>{item.exerciseName}</td>
            <td>{item.instructions}</td>
          </tr>
        );
    }
    

    Working example:

    function Row({item, index}) {
      return (
        <tr>
          <td>{index}</td>
          <td>{item.exerciseName}</td>
          <td>{item.instructions}</td>
        </tr>
      );
    }
    function App() {
      const data = [{exerciseName: 'Name 1', instructions: 'Instructions 1'}, {exerciseName: 'Exercise 2', instructions: 'Instructions 2'}];
      return (
        <table>
          <tbody>
            {data.map((item, index) => (
                <Row key={index} item={item} index={index}/>
            ))}
          </tbody>
        </table>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
    table, td {
      border: 1px solid;
      border-collapse: collapse;
      padding: 5px;
    }
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <div id="root"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search