Reputation: 325
I am trying to update the color using react on a set of boxes using onClick and value.
I've tried several different methods and it didn't work. I would ultimately like to have the colors align with the different changes in the tic tac toe game.
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value},
{props.style},
</button>
);
}
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
backgroundColor: 'gray';
squares: Array(9).fill(null),
xIsNext: true,
};
}
handleClick(i) {
const squares = this.state.squares.slice();
const { containerStyle } = styles;
squares[i] = this.state.xIsNext ? 'X' : 'O';
backgroundColor = this.state.xIsNext ? 'blue' : 'red';
this.setState({
backgroundColor: 'someNewColor',
squares: squares,
xIsNext: !this.state.xIsNext,
});
}
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
color={this.state.backgroundColor}
onClick={() => this.handleClick(i)}
/>
);
}
Upvotes: 0
Views: 416
Reputation: 11247
I am not sure how you are rendering, there seems to be many issues with your code.
Here is the working code, and background color being changed on click of square.
Not the whole code but this will give you gist how you should code.
import React from "react";
import ReactDOM from "react-dom";
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
backgroundColor: 'gray',
squares: Array(9).fill(null),
xIsNext: true,
};
}
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
backgroundColor: this.state.xIsNext ? 'yellow': 'red',
squares: squares,
xIsNext: !this.state.xIsNext,
});
}
renderSquare(i) {
return (
<Square
value={this.state.squares[i] || 'X'}
color={this.state.backgroundColor}
onClick={() => this.handleClick(i)}
/>
);
}
render () {
return (<div>
{this.renderSquare(1)}
</div>);
}
}
function Square(props) {
return (
<button className="square" onClick={props.onClick} style={{ backgroundColor: props.color}}>
{props.value}
</button>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Board />, rootElement);
Hope that helps!!!
Upvotes: 1