How to go to another page onClick in react How to go to another page onClick in react reactjs reactjs

How to go to another page onClick in react


If you really want to build a single app I'd suggest using React Router. Otherwise you could just use plain Javascript:

There are two main ways of doing depending on your desire you want to:

  1. Style an <a> as your button
  2. Use a <button> and redirect programatically

Since according to your question my assumption is that you're not building a single page app and using something along the lines of React router. And specifically mentioned use of button Below is a sample code

var Component = React.createClass({  getInitialState: function() { return {query: ''} },  queryChange: function(evt) {    this.setState({query: evt.target.value});  },  handleSearch: function() {    window.location.assign('/search/'+this.state.query+'/some-action');  },  render: function() {    return (      <div className="component-wrapper">        <input type="text" value={this.state.query} />        <button onClick={this.handleSearch()} className="button">          Search        </button>      </div>    );  }});

Mistakes I see according to your post

  1. The function which uses window.location is not properly called in render method
  2. You could use window.location.assign() method which helps to load new document
  3. I doubt that JSX pages are rendered directly in browser level when you try to call them directly

Hope this would help, if not and you figure out an answer please share


You need to bind the handler in the constructor of your component, otherwise React won't be able to find your home function.

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


You need to reference the method using this, otherwise React does not find it.

<div>  <img className="menu_icons" src={myhome}/>  <label className="menu_items" onClick={this.home}>Home</label></div>