Jota
Jota

Reputation: 865

How to add an element in the your index inside a array? ReactJs

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..

Upvotes: 0

Views: 3687

Answers (4)

Miguel Anci&#227;es
Miguel Anci&#227;es

Reputation: 106

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

Upvotes: 1

Ricardo Amaral
Ricardo Amaral

Reputation: 31

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;

Upvotes: 1

ic3b3rg
ic3b3rg

Reputation: 14927

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.

Upvotes: 1

Juorder Gonzalez
Juorder Gonzalez

Reputation: 1652

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

Upvotes: 2

Related Questions