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?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Onur Şahal
  • 109
  • 3
  • 13

1 Answers1

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.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • i tried your first solution and nothing happen but second, im getting 'this.props is undefined' – Onur Şahal Feb 06 '18 at 13:44
  • i solved finally. i put link outside of button and worked . – Onur Şahal Feb 06 '18 at 13:57
  • 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)`. – Mayank Shukla Feb 06 '18 at 14:12
  • I still dont understand bind logic but thank you again – Onur Şahal Feb 06 '18 at 14:33
  • 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?](https://stackoverflow.com/questions/41391288/why-is-javascript-bind-necessary) – Mayank Shukla Feb 06 '18 at 14:40
  • Yeap it worked too.Now im looking your link thank you so much. – Onur Şahal Feb 06 '18 at 14:42