Home > Mobile >  index of the elements in the array returns an object
index of the elements in the array returns an object

Time:07-24

I have a simple example as below. I want to get the index of each Test component.

But key value returns object. I'm not very familiar with Reactjs, how can I get the index of each component?

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";

function App() {
  const [component, setComponent] = useState([]);

  useEffect(() => {});

  const Test = observer((inputs, key) => {
    console.log(inputs);
    console.log(key);
    return (
      <div>
        {/* 
        I want to use it this way.
        <p>Test {key} </p> */}
        <p>Test </p>
      </div>
    );
  });

  return (
    <div>
      {component.map((Input, index) => (
        <Input inputs={component} key={index} />
      ))}
      <button onClick={() => setComponent([...component, Test])}>
        Click me
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesandbox: https://codesandbox.io/s/react-hooks-useeffect-forked-cc5nb1

CodePudding user response:

The key property is used by React under the hood, so you need to pass it under a different name like index

{component.map((Input, index) => (
  <Input inputs={component} index={index} key={index} />
))}

and then access it like this:

const Test = observer(({ inputs, index }) => {
    console.log(index);
    console.log(inputs);
    return (
      <div>
        {/* 
        I want to use it this way.
        <p>Test {key} </p> */}
        <p>Test </p>
      </div>
    );
  });
  • Related