Home > database >  How to disable a button once clicked in JSX, ReactJs?
How to disable a button once clicked in JSX, ReactJs?

Time:11-22

I'm making a 2 player tic tac toe game and I can not find out how to prevent a player from clicking on a square that has already been clicked on.

Currently if a player clicks on a X/O already present it changes the state to O/X . I want to disable that.

Board.js

import React, { useState } from 'react'
import Square from './Square'

export default function Board () {

  const [xIsNext, setXIsNext] = useState(true);
  const [squares, setSquares] = useState(Array(9).fill());

  const renderSquare = (i) => {
    return <Square 
      squares={squares[i]} 
      handleClick={()=>handleClick(i)}
    />;
  }

  const handleClick = (i) => {
    const newSquares = squares.slice();
    newSquares[i] = xIsNext ? 'X' : 'O';
    setSquares(newSquares);
    setXIsNext(!xIsNext);
  }

  const status = 'Next player: '   (xIsNext ? 'X' : 'O');

  return (
    <div>
      <div className="status">{status}</div>
      <div className="board-row">
        {renderSquare(0)}
        {renderSquare(1)}
        {renderSquare(2)}
      </div>
      <div className="board-row">
        {renderSquare(3)}
        {renderSquare(4)}
        {renderSquare(5)}
      </div>
      <div className="board-row">
        {renderSquare(6)}
        {renderSquare(7)}
        {renderSquare(8)}
      </div>
    </div>
  );
}

Square.js

import React from "react";

export default function Square ({ squares, handleClick, disabled })  {
  return (
    <button className="square" onClick={()=>handleClick()} disabled={disabled}>
      {squares}
    </button>
  );
}

I've used state to prevent clicking on a button already pressed, but it disables all the button in the game rather than just the one that was pressed.

CodePudding user response:

You should add the disabled prop to your Square with a value based on if the square has data or not, e.g.

const renderSquare = (i) => {
    return <Square 
      squares={squares[i]} 
      handleClick={()=>handleClick(i)}
      disabled={!!squares[i]}
    />;
  }
  • Related