Redirect pages using useHistory and remove image when click is false

Viewed 223

enter image description here

With useEffect I tried to compare the right sequence with the right clicks and if it is true, automatically redirect to another page. If you make a mistake four times you will be redirected to the Loose page, with each error remove an image. How do I redirect the pages and how do I delete the images as the click is false?

useEffect(() => {
const correctSequence = [4, 5, 7, 8, 9];
if (correctSequence === sequence) {<Redirect to="/Win" />;
} else {<Redirect to="/Loose" />;}
console.log(sequence);
console.log(correctSequence);}, [sequence]);

Demo

2 Answers

You can't directly redirect from useEffect using <Redirect />, you will need:

props.history.push('/Win')

Same for /Loose.

Don't forget to wrap your component with withRouter.

you can use useHistory() react hook. Make a function that checks if the orders are right and use history.

const history = useHistory();

const correctSequence = [4, 5, 7, 8, 9];

const compare = () => {
  if (correctSequence === sequence){
    history.push("/Win");
  } else {
    history.push("/Loose");
  }
}

Related