How can I add a button inside a clickable row in a table

Viewed 37

I am not sure if this is even possible but I have a table that has an onClick event on each row that directs the user to another page. I need to add a button inside each row to handle a separate event. But everytime I click the button the action to redirect to a new page is fired. Is it possible to have a click event inside another?

example:


items.map((item) => {
  return(
    <tr onClick={onClick(item.value)}>
      <td>{item.Name}</td>
      <td>
         {visitCreated}
          <span>
            <button 
              type="button" 
              onClick={handlePreview(item.referenceID)}>
                  Preview
            </button>
          </span>
       </td>
      <td>{item.Encounters}</td>
    </tr>
})

Anytime I click the both events are triggered. How can I isolate them?

3 Answers

The fastest way would be to wrap the onClick handlers in an arrow function:

onClick={()=>onClick(item.value)}

onClick={()=>handlePreview(item.referenceID)}
items.map((item) => {
  return(
    <tr onClick={()=>onClick(item.value)}>
      <td>{item.Name}</td>
      <td>
         {visitCreated}
          <span>
            <button 
              type="button" 
              onClick={()=>handlePreview(item.referenceID)}>
                  Preview
            </button>
          </span>
       </td>
      <td>{item.Encounters}</td>
    </tr>
})

You can add an id on the button, and check if the target has this id to prevent one or the other event. Something like

function onClick(event) {
    if (event.target.id !== 'button_id') {
      // do something
    }
    event.stopPropagation()
}

function handlePreview(event) {
     if (event.target.id === 'button_id') {
      // do something else
    }
    event.stopPropagation()
}

...

 items.map((item) => {
      return(
        <tr onClick={onClick(item.value)}>
          <td>{item.Name}</td>
          <td>
             {visitCreated}
              <span>
                <button 
                  type="button" 
                  id="button_id"
                  onClick={handlePreview(item.referenceID)}>
                      Preview
                </button>
              </span>
           </td>
          <td>{item.Encounters}</td>
        </tr>
})
Related