How to highlight a row from the table when it is clicked? I have tried using onClick
function but I cannot achieve it.
This is the function I used for mapping the table data to td tag.
displayData() {
let x;
if (this.props.data) {
x = this.props.data.map(item => (
<tr>
<td> {item.height} </td>
</tr>
));
}
return x;
}
Here I have called this function inside the render function.
<Table id="tableId" >
<thead>
<tr>
<th> height </th>
</tr>
</thead>
<tbody> {this.displayData()} </tbody>
</Table>
You have to provide an key
to every td
, then a className
property that will change depending on the id existing currently in the state
and of course an onClick
event handler that will fill in the state with the clicked id, therefore this block:
if (this.props.data) {
x = this.props.data.map((item,key) => (
<tr>
<td
key={key}
onClick={this.handleCellClick(key)}
className={`${this.state.checkedId===key? 'highlighted-cell': ''}`}
> {item.height} </td>
</tr>
));
}
and your handleCellClick
function can be implemented as follows:
handleCellClick = (key) => (event) => {
if(this.state.checkedId===key){
this.setState({
checkedId: '',
});
}else{
this.setState({
checkedId: key,
});
}
}
finally your highlited-cell
class can be written as per your preferences:
.highlighted-cell {
background-color: blue;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.