Search code examples
reactjsrowhighlight

Only highlight table rows that are clicked on in React


I currently have a class that renders the output of state data into a table. But I want to be able to highlight rows based on a unique id that each state array has.

Here is the function and render code for the table contents:

toggleActive(id) {
this.setState({
  rowIsActive: id,
});
if (rowIsActive === id) {
}
}

render() {
const EventsList = this.props.eventList.map((event) => {
  return scenario.list.map((event) => {
    return (
      <TableRow
        className="tr"
        key={event.id}
        handleClick={() => this.toggleActive(event.id)}
      >
        <Table.Td className="td">{event.name} </Table.Td>
        <Table.Td>
          <div>{event.location}</div>
          <div>{event.numberofpeople}</div>
          <div>{event.host ? event.host : null}</div>
          <div>{event.type ? pickevent.type : null}</div>
          <div>{event.style ? event.style : null}</div>
        </Table.Td>
        <Table.Td>{event.country}</Table.Td>
      </TableRow>
    );
  });
});
return <Fragment>{EventsList}</Fragment>;
  }
}

How would I go about implementing this using React or CSS?


Solution

  • This example will work if you need to highlight only one row

    toggleActive(id) {
      this.setState({
         rowIsActive: id,
      });
    }
    
    render() {
      const EventsList = this.props.eventList.map((event) => {
        return scenario.list.map((event) => {
          return (
            <TableRow
              className={`tr ${this.state.rowIsActive === event.id ? 'active' : ''}`}
              key={event.id}
              handleClick={() => this.toggleActive(event.id)}
            >
              <Table.Td className="td">{event.name} </Table.Td>
              <Table.Td>
                <div>{event.location}</div>
                <div>{event.numberofpeople}</div>
                <div>{event.host ? event.host : null}</div>
                <div>{event.type ? pickevent.type : null}</div>
                <div>{event.style ? event.style : null}</div>
              </Table.Td>
              <Table.Td>{event.country}</Table.Td>
            </TableRow>
          );
        });
      });
    
      return <Fragment>{EventsList}</Fragment>;
    }