0

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','','','','',''].

I tryed do, but gave error: enter image description here

Someone would can help me ? Please..

4
  • what is the error message? Commented May 30, 2018 at 0:00
  • It is the print, it add in the end of the array :( Commented May 30, 2018 at 0:01
  • Never mutate props passed to you. Pass down a callback from the parent to the child which the child calls, and, have the parent callback call setState Commented May 30, 2018 at 0:02
  • try .splice(position, 0, player) instead of pushing Commented May 30, 2018 at 0:04

4 Answers 4

2

You need to use a splice function, to put an item into a specific position

so you should do it like

position.splice(thePosition, 0, valueToBeInserted);

you can read its docs in https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/splice

Sign up to request clarification or add additional context in comments.

Comments

1

The position.push() method will only add to the array. To affect a certain position of an array you need:

this.state = {
 board: Array(9).fill('') 
}

this.state.board[1] = 'X'

The last line of code will replace the current value on the 1st position of the board variable with a 'X' character giving you:

["", "X", "", "", "", "", "", "", ""]

Hope it helps.

UPDATE

My understanding is that the slice() method will insert a element into the middle of the array. As a result, it will grow. I think that is not your objective

UPDATE

You should always use the setState() function to update the state of a component

Comments

1

You can change

position.push(currentUser);

to

position.splice(value, 1, currentUser);

next step: pass a handler down to Square that updates the state in App instead of mutating the state in Square.

Comments

1

You're using:

position.push(currentUser);

this adds the element 'currentUser' to the array. That's not what you want!

You should instead do:

position[i] = currentUser;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.