0

I would like to be able to click a button and navigate to another page on the site.

I have tried to use the code from this page but cannot make it fit into my code. I have also got this code from another page.

Any help appreciated.

React route example

import React from 'react';

class Home extends React.Component{
    constuctor() {
        this.routeChange = this.routeChange.bind(this);
      }

    routeChange() {
        let path = '/CreateAccount';
        this.props.history.push(path);
      }      

    render(){
        return(

          <div>
          <p>
                <button         
                onClick={this.routeChange}
                class="btn btn-lg btn-gradient"
                >
                    Signup                        
                </button></p>
          </div>
            )
          }
    }
Asmtony
  • 138
  • 1
  • 4

1 Answers1

0

You need to bind the function to the correct this. The easiest method is use an ES6 arrow function for routeChange. If you don't, the this in routeChange is the originator of the click, rather than the component.

Arrow functions are automatically bound to the this of the containing instance.

routeChange = ()=> {
    let path = '/CreateAccount';
    this.props.history.push(path);
  }  

There are other ways to solve this problem such as patching it in the constructor:

constructor( props ){
    super( props );
    this.routeChange = this.routeChange.bind(this);
  }

... but arrow functions are a lot simpler and more convenient imo.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46