Atul
Atul

Reputation: 1711

Programmatically navigating using react-router

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.

Upvotes: 1

Views: 455

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104379

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;

Upvotes: 1

Related Questions