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!

jmsapps
  • 388
  • 2
  • 17

1 Answers1

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

A G
  • 21,087
  • 11
  • 87
  • 112
  • 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 – jmsapps Jun 02 '22 at 18:16
  • You can pass the event as `onClick={(event) => handleClick(event, user)}`. I have updated the answer & codesandbox. – A G Jun 02 '22 at 18:21