i'm doing the game Tic Tac Toe, but i have a problem..
I want to add the element in an array in the position that was passed.
My app.js:
import React, { Component } from 'react';
import './App.css';
import Square from './Square.js';
import './Square.css';
class App extends Component {
constructor() {
super();
this.state = {
board: Array(9).fill(''),
currentUser: 'X',
position: Array(9).fill(''),
}
}
changeUser = () => {
this.setState({
currentUser: this.state.currentUser === 'X' ? "O" : "X",
})
}
render() {
return (
<div id="game">
<div id='head'>
<h5> Tic Tac Toe Jcsouz Games </h5>
</div>
<div id="board">
{this.state.board.map((v, i) => <Square position={this.state.position} value={i} key={i} changeUser={this.changeUser} currentUser={this.state.currentUser}>
{props => (<span>{props}</span>)}
</Square>
)}
</div>
</div>
);
}
}
export default App;
Square.js (where i do the push);
import React from 'react';
import './Square.css';
class Square extends React.Component {
constructor() {
super();
this.state = {
player: '',
}
}
changePlayer = () => {
const { changeUser, value, position, currentUser } = this.props;
position.push(currentUser);
changeUser();
if (this.state.player === '') {
this.setState({
player: this.props.currentUser,
})
}
}
render() {
return (
<div className="square" onClick={this.changePlayer}>
{this.props.children(this.state.player)}
{this.props.children(this.state.position)}
</div>
)
}
}
export default Square;
What needs to happen: Each square has its index (from 0 to 8), I wanted it, for example: If I clicked on the square number 0, it added the value of it in the array in position 0 ['X','','','','','','','',''], or if I clicked on square 4, Position 4 ['','','','X','','','','',''].
Someone would can help me ? Please..

setState.splice(position, 0, player)instead of pushing