0

I am trying to use react-router navigation in a button.

dashboard.js

handleClick() {
   <Link to="/deneme">Deneme</Link>;
   console.log('clicked!');
}

<Button color="primary" onClick={this.handleClick}>Hesapla</Button>

And i configured my route like:

index.js

<HashRouter>
  <Switch>
    <Route path="/" name="Home" component={Full}/>
  </Switch>
</HashRouter>

Full.js

<Switch>
    <Route path="/dashboard" name="Dashboard" component={Dashboard} />
    <Route path="/deneme" name="Deneme" component={Deneme} />
</Switch>

handleClick working but link doesn't work. Any suggestion?

0

1 Answer 1

2

Link is a ui element, you have to render it inside render method and onClick of that link will take you to that page, putting Link inside a method will not redirect you to that page.

You have two options:

1- Put that Link inside render method where you define the handle click, means like this:

<Button color="primary">
    <Link to='/deneme'>Hesapla</Link>
</Button>

And remove handleClick method.

2- Another way is, navigate dynamically by pushing the route into history, like this:

handleClick() {
   this.props.history.push('/deneme');
}

For more details check this answer: How to navigate dynamically using react router dom

Assuming you are using React-Router V4.

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

6 Comments

i tried your first solution and nothing happen but second, im getting 'this.props is undefined'
i solved finally. i put link outside of button and worked .
great, you got the solution, i think reason for this.props is undefined, is you forgot to bind the handleClick method, put this line in the constructor: this.handleClick = this.handleClick.bind(this).
I still dont understand bind logic but thank you again
is it working after binding? check this answer you will get a better idea why and when binding is required: Why is JavaScript bind() necessary?
|

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.