This is the code, so I have a component which renders a columns of intervals and I want to change the color of the table on click and drag but what happens is instead it changes everything... I'm a complete beginner, So I have really no idea how will I do that..
import React, { Component } from 'react';
class TableBody extends Component {
constructor(props) {
super(props);
this.state = {
intervalItems: this.props.intervalItems,
flag: 0,
bgColor: '',
};
}
_mouseDown() {
this.setState(prevState => ({
flag: 1,
}));
}
_mouseUp() {
this.setState(prevState => ({
flag: 0,
}));
}
_mouseDrag(iD) {
if (this.state.flag == 1) {
this.setState(prevState => ({
bgColor: 'green',
}));
} else {
this.setState(prevState => ({
bgColor: '',
}));
}
}
render() {
const { dayItems, intervalItems } = this.props;
return (
<tbody>
{dayItems.map(v => (
<tr key={v.id}>
<th>
<div>{v.day}</div>
</th>
{this.state.intervalItems.map((v, i) => (
<td
key={v.id}
onMouseDown={() => this._mouseDown()}
onMouseMove={() => this._mouseDrag()}
onMouseUp={() => this._mouseUp()}
className={`table-inside-default ${this.state.bgColor}`}
>
{v.interval}
</td>
))}
</tr>
))}
</tbody>
);
}
}
export default TableBody;
It looks like what's happening is that you're updating the color for all of your <td> tags at once. This is happening because they are all referencing the same piece of state, this.state.bgColor. When one td is changed, the component is re-rendered and all the elements pointing to this.state.bgColor will show up as the same color.
You might consider adding another property to your state, such as this.state.activeItem, and update it from your _mouseDrag function. Based on your activeItem, you can then set a designated color so that only that one is being updated. You might want to reset the activeItem in a separate function so that it gets cleared in between mouse events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With