0

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 ?

2
  • it's logging without you clicking isnt it? Commented Mar 1, 2022 at 13:19
  • This won't log anything to the console, this will produce syntax errors in the console: onClick={console.log(user.id}) When providing a minimal reproducible example in the question, it's important to test that example and validate that it actually demonstrates the problem you're trying to solve. Commented Mar 1, 2022 at 13:21

3 Answers 3

3

[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)}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

onClick function takes a callback function so you have to write the code in this way:

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

Comments

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.