I'm new to web development world, especially to React JS. Here I'm trying to create a Tic-Tac-Toe game using React JS. The problem is when I try to click, it changes all other components as well, not only one. I know it's because I pass status to all divs
, but I can't figure out how do I change only clicked component.
I've searched a lot and found many Tic-Tac-Toe games which are used React JS, but I couldn't figure out how they work (mainly because of .map()
). Can you guys please help with examples and explanations why you did so? And can someone explain how .map()
works in React JS. I know how .map()
works in general, but with React JS code I really got confused.
var Game = React.createClass({
getInitialState: function() {
return {
status: " ",
turn: 'o',
clicks: 0
};
},
clickHandler: function() {
var newClicks = this.state.clicks + 1;
var newMark = newClicks%2 ? 'X' : 'O';
if ((status === 'X' || status === 'O')){
return;
}
this.setState({
status: newMark,
clicks: newClicks
});
},
render: function() {
return <div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
<div className="box" onClick={this.clickHandler}><h1>{this.state.status}</h1></div>
</div>
}
});
React.render(
<Game />, document.getElementById('container')
);
.map()
. – user3053089map
. As written, this won't work. There's lots of great explanations ofmap
as well, so what is it that you don't understand about it specifically? In typical cases, code iterates through an array of "something" and converts each element to a React component. – WiredPrairie