Reputation: 4322
I have a table I've built in React. I want to be able to color a cell if I click on it, and uncolor it if I click on a different cell (the new cell would get colored instead).
I can successfully color cells when I click on them, but I'm not sure how to uncolor them, since the cell object doesn't know when a different cell has been clicked on. (I can't think of anything in the row/table object that would know either, though.) As a result, I end up with a bunch of colored cells if I click multiple times, instead of just one.
Here is my cell code:
class Cell extends React.Component {
state = {
bgColor: 'inherit'
}
handleClick = (columnId) => {
this.setState({
bgColor: "blue"
})
}
render() {
const content = this.props.content;
return (
<td
onClick={()=> this.handleClick()}
style={{backgroundColor: this.state.bgColor}}
>
{content}
</td>
)
}
}
Thanks in advance for your help!
Upvotes: 1
Views: 352
Reputation: 14191
I can successfully color cells when I click on them, but I'm not sure how to uncolor them, since the cell object doesn't know when a different cell has been clicked on
You need a single source of truth so that your components know who is active. In the example below, I put the activeCell
state on a parent component App
so that this will hold the true value of who is active. Pass the props down the to Cell
as needed for the updating of the new activeCell
on-click
class Cell extends React.Component {
render() {
const content = this.props.content;
return (
<td
onClick={()=>{this.props.handleChangeActiveCell(this.props.identifier)}}
style={{backgroundColor: this.props.activeCell === true ? this.props.bgColor : 'inherit'}}
>
{content}
</td>
)
}
}
class App extends React.Component {
state = {
bgColor: "blue",
activeCell: -1
}
handleChangeActiveCell = (key) => {
this.setState({
activeCell: key
});
}
render(){
return(
<React.Fragment>
<table>
<tr>
<Cell
identifier={0}
handleChangeActiveCell={this.handleChangeActiveCell}
activeCell={this.state.activeCell === 0 ? true : false}
bgColor={this.state.bgColor}
content={`sample_content`}
/>
<Cell
identifier={1}
handleChangeActiveCell={this.handleChangeActiveCell}
activeCell={this.state.activeCell === 1 ? true : false}
bgColor={this.state.bgColor}
content={`sample_content`}
/>
</tr>
</table>
</React.Fragment>
);
}
}
ReactDOM.render(<App/>, document.getElementById("root"));
td {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1