1

I am trying to redirect to new page via onclick function of a button, but its not redirecting.

Here is my code-

import React from 'react'; import { withRouter } from 'react-router-dom'; class Pricing extends React.Component { constructor(props){ super(props); document.title = "Pricing"; this.setPlanId = this.setPlanId.bind(this); } setPlanId(p_id){ localStorage.setItem('plan_id', p_id); //BrowserRouter.push('/do-payment'); this.props.history.push("/do-payment"); } render(){ return( <div> <div className="pricing bottommargin clearfix"> <Link to="#" className="btn btn-danger btn-block btn-lg bgcolor border-color" onClick={this.setPlanId(somevalue)}>Contunue</Link> </div> </div> ); } } export default Pricing; 

Please let me know, what I am doing wrong.

4
  • First of all it should be onClick={this.setPlanId}. Then are you sure you can use BrowserRouter this way?CommentedJun 15, 2017 at 11:51
  • Possible duplicate of how-to-navigate-dynamically-using-react-router-domCommentedJun 15, 2017 at 11:54
  • 1
    @MayankShukla , yes its duplicate and I applied same import { withRouter} from 'react-router-dom'; and this.props.history.push("/do-payment"); in respective function. .............but its redirecting automatically without on click event...
    – Atul
    CommentedJun 15, 2017 at 12:02
  • actually I am passing value to function to set in localStorage. Please check updated code in question.
    – Atul
    CommentedJun 15, 2017 at 12:06

1 Answer 1

1

First question was duplicate of: How to navigate dynamically using react router dom

Answer of updated Ques.

Write it like this:

render(){ return( <div> <div className="pricing bottommargin clearfix"> <Link to="#" className="btn btn-danger btn-block btn-lg bgcolor border-color" onClick={() => this.setPlanId(somevalue)} > Contunue </Link> </div> </div> ); } 

Reason:onClick expect a function but you are assigning a value by calling that function, you don't need to call that method it will get called whenever user click on that.

Use arrow function like this:

onClick={() => this.setPlanId(somevalue)} 

or

onClick={this.setPlanId.bind(this, somevalue)} 

And remove the method binding from constructor that will not be required after this.

Full Code:

import { withRouter } from 'react-router-dom'; class Pricing extends React.Component { constructor(props){ super(props); document.title = "Pricing"; } setPlanId(p_id){ localStorage.setItem('plan_id', p_id); this.props.history.push("/do-payment"); } render(){ return( <div> <div className="pricing bottommargin clearfix"> <Link to="#" className="btn btn-danger btn-block btn-lg bgcolor border-color" onClick={() => this.setPlanId(somevalue)}>Contunue</Link> </div> </div> ); } } export default Pricing; 

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.