0

I'm a beginner working on a simple CRUD, and all I want to do is get the user from the selected row. If you look below:

      {/* ANCHOR - TABLE ROWS */}
      {admins.map((user, index) => (
          <tbody key={index}>

            <tr>
              <td style={{fontWeight: 'bold'}}>{user._id}</td>
              <td>{shortenStr(user.username)}</td>
              <td>{shortenStr(user.firstName)}</td>
              <td>{shortenStr(user.lastName)}</td>
              <td>{shortenStr(user.dob)}</td>
              <td>

                <div className="button-div">
                  <button id="updateUser" 
                  className="button-update-admin" 
                  onClick={handleClick && console.log(user.firstName)}>
                  </button>
                </div>

              </td>
            </tr>

            </tbody>
      ))}

Console.log gives me the first names of every user in the table, such as:

John
Steve
Frank

Ideally I would like to pass the user Data into my handle click function so that I can create a context, perhaps. Any help is appreciated, thanks!

2
  • what does handleClick do? Commented Jun 2, 2022 at 17:43
  • onClick={handleClick(user.firstName)}? Commented Jun 2, 2022 at 18:21

1 Answer 1

4

Please change -

onClick={handleClick && console.log(user.firstName)}>

To

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

Or if you want to have a separate onClick function with the event data -

function handleClick(event, user) {
    console.log(user.firstName);
}
...
onClick={(event) => handleClick(event, user)}

Edit purple-tdd-ly0263

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

2 Comments

How do I pass a parameter into an onClick function if I have an event, such as: const handleClick = (event: MouseEvent, firstName: string) => {}. In other words how do I pass the event as an argument? For example: onClick={handleClick(event, user.firstName)} this doesnt work, and removing the event gives me an error: Expected 2 arguments, got 1
You can pass the event as onClick={(event) => handleClick(event, user)}. I have updated the answer & codesandbox.

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.