Home > Blockchain >  How can I get user.id from a component in React
How can I get user.id from a component in React

Time:03-02

I need to get user.id but i don't know how.

function App() {
  const users = 
  [
    {id: 1, name: "Gabriel", idade: 25},
    {id: 2, name: "Beatriz", idade: 26}
  ]

  return (
    <div>
      {users.map((user) => 
      <div className='App'>
        <p>
          {user.id} {user.name} {user.idade}
        </p>
        <button onClick={console.log(user.id})>Clique aqui</button>
      </div>
      )}
    </div>
  );
}

export default App;

When I console.log(user.id) return all ids in Array. Someone can help me ?

CodePudding user response:

[After correcting obvious typos and syntax errors in your code...]

This isn't doing what you think it does:

onClick={console.log(user.id)}

This executes console.log(user.id) immediately when rendering, and set the onClick handler to the returned value (which is undefined). If you want to execute a function on click then you need to provide a function to be called, not just call a function:

onClick={() => console.log(user.id)}

CodePudding user response:

You should do like this. Your onClick function is wrong

  <button onClick={()=> console.log(user.id)}>Clique aqui</button>

https://codesandbox.io/s/polished-pond-2ssx83?file=/src/App.js:322-388

  • Related