1

I hope this question hasn't been answered yet somewhere and I haven't found it... So I'm still new to React.js but always trying new things with it, anyways.

I've already done my research but none of the proposed solutions seem to work for me. I'll leave some examples of what I've search for:

How to use Redirect in the new react-router-dom of Reactjs

Redirecting in React

React-router route won't trigger

So I basically have this piece of code:

clicked(mousePosX, mousePosY) {
 let d = property.dist(mousePosX, mousePosY, this.x, this.y);
 if (d < this.w && d < this.h) {
  console.log("square"); //working until here
  return <Link to="/test/" />; //not redirecting
 }
}

I have it inside a class which creates a square with help from the p5 library which is also inside a const arrow function.

I've also tried to change the Link tag to a Redirect tag, no luck.

If you'd like to see the whole file (or project) here's a link:

Whole file (github)

What I want it to do is to redirect the user somewhere else after the user clicks on any on-screen square.

I'll be thankful for any help. Thanks in advance.

Sarquamon
  • 49
  • 2
  • 8
  • `` doesn't redirect to somewhere else untill you click on it, to redirect programmatically you need to use `` component. – Gulam Hussain Nov 29 '19 at 04:42

2 Answers2

2

<Link/> doesn't redirect to somewhere else untill you click on it, to redirect programmatically you need to use <Redirect/> component.

Update your clicked function, when user clicks on the square box, set redirect variable to true in state. and in render function check if redirect is true, if it's true then use <Redirect/> component to redirect somewhere else otherwise return your other UI component.

Here is how a basic state setup should look like-

constructor(props){
    super(props);
    this.state = {
        redirect: false,
        //other state data
    }
}
clicked(mousePosX, mousePosY) {
 let d = property.dist(mousePosX, mousePosY, this.x, this.y);
 if (d < this.w && d < this.h) {
  console.log("square"); 

  this.setState({
    redirect:true, //set redirect to true
  });

 }
}

In your render function

render(){
    if(this.state.redirect){
        return <Redirect to="/test" />
    }
    else{
        //return something else
    }
}
Gulam Hussain
  • 1,591
  • 10
  • 19
0

link tag should be used with any html tag as follows https://reacttraining.com/react-router/web/guides/quick-start