reactjstypescriptonclickreact-tablereact-button

Getting an object from a table row in React


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!


Solution

  • 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