0

Hi I'm just wondering is there any feature in React.js that allows you block user from clicking on some part of app?

To be more clear I'm working on Tic tac toe app and I would like to block any other clicks to game field if someone wins.

After checkWinner function detects a win, winner is displayed above game field like this

enter image description here

and from now I would like to make that user can click only replay icon or return icon. nothing else.

Part of my checkWinner function in which I've tried to use e.stopPropagation()

  function checkWinner(e){
    //Horizontal check
    for(let i=0;i<values.length;i++){
      let xCount=0;
      let oCount=0;

      for(let j=0;j<values[i].length;j++){
        if(typeof values[i][j] === 'object' && values[i][j].props.children === 'x'){
          xCount++;
        }

        if(typeof values[i][j] === 'object' && values[i][j].props.children === 'o'){
          oCount++;
        }
      }

      if(xCount === 3){
        setWinner('X WINS!');
        displayWinner();
        e.stopPropagation();
      }
    }

This function is called after every click to field, so after every click it checks if someone wins. But this throws me an Error TypeError: Cannot read property 'stopPropagation' of undefined

Do you guys know about any other approach for this situation? Thanks.

2
  • The react tutorial covers this same sample app. Have you checked their approach? Commented Oct 22, 2020 at 16:36
  • "TypeError: Cannot read property 'stopPropagation' of undefined" That error strikes me as very clear. Are you passing in the event object where you call checkWinner()? Commented Oct 22, 2020 at 16:56

1 Answer 1

1

To disable click you can use CSS property pointer-events: none;

Example to disable click

 function App() {
  const [counter, setCounter] = React.useState(0);
  const handleClick = () => {
    setCounter(counter + 1);
  }
  let disableClass = counter < 5 ? '' : 'disable';
  return (
    <div className="App">
      <h1>Disable button to click after 5</h1>
      <button 
      className={disableClass}
      onClick={handleClick}>Click</button>
      <h3>{counter}</h3>
    </div>
  );
}

css

.disable {
  pointer-events: none;
  border: none;
  padding: 8px 15px;
  background: red;
  color: white;
}

you can follow this and make changes as per your requirement. for more reference check this pointer-events

Live working demo

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

3 Comments

Thank you for your answer. Can I ask you for one more thing? :/
@Pinncik yeah tell me.
Do you have any experience with animating react-router-dom routes with react-spring?

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.