0

I am using DataTable component from prime-react in my React application to create a data table. I want to change the colour of the row when it's double clicked. However, when another row is clicked, the colour of the previous highlighted row should be changed back to original colour. I went through the docs but prime-react doesn't seem to provide an API to change row colours. So what will be the best way to achieve this?

I can change the row colour like this but I don't see an efficient way to change back colours of all other rows. Plus it's not a good practice to use vanilla JavaScript to modify DOM?

  const highlightRow = event => {
    event.originalEvent.currentTarget.classList.add('highlighted-row');
  };

  <DataTable
     value={props.values}
     onRowDoubleClick={event => highlightRow(event)}
   >

CSS:

.highlighted-row {
    background-color: blue;
}
darKnight
  • 5,651
  • 13
  • 47
  • 87
  • React is a declarative library not imperative. You should maintains a state of rows color. So on rowDoubleClick event handler you should update this state. – Alexandre Nicolas Mar 10 '20 at 13:59

2 Answers2

0

You should keep track of the currently double clicked row using state (https://reactjs.org/docs/state-and-lifecycle.html) You then can probably use the selection prop in that component

selection={this.state.selectedCar1} onSelectionChange={e => this.setState({selectedCar1: e.value})}

Check this example https://www.primefaces.org/primereact/showcase/#/datatable/selection

Luis Gurmendez
  • 654
  • 4
  • 10
  • I can't use `selection` prop for this because it's not really selection. In fact, I am already using `selection` prop for actual selections. In my case I just want to display the corresponding data for that row when user double clicks on it, but this doesn't mean that the user has selected that row. Selection in my app is done by clicking the corresponding check box. – darKnight Mar 10 '20 at 17:01
0

I figured it out. I am keeping the last clicked row in my component state. Then whenever user clicks another row, I first remove the highlighted-row css class from that row, and then I update component state with the new row as the current highlighted row. I then add the highlighted-row class to this row.

const [, highlightComponent] = useState(null);

const highlightComponentOnRowClick = row => {
  const highlightedNode = row.originalEvent.currentTarget;
  highlightComponent(previousHighlight => {
    previousHighlight && previousHighlight.classList.remove("highlighted-row");
    highlightedNode && highlightedNode.classList.add("highlighted-row");
    return highlightedNode;
  });
  dispatch(setHighlightedComponent(row.data.component_id));
};
darKnight
  • 5,651
  • 13
  • 47
  • 87