Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go to another page onClick in react

I'm new to react and i'm trying to load another page when user clicks a button. I have used window.location but nothing happens when i click the button. How to fix this?

This where i have included my onClick

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

Function written for onClick

function home(e) {
    e.preventDefault();
    window.location = 'my-app/src/Containers/HomePage.jsx';
}
like image 235
CraZyDroiD Avatar asked Feb 20 '17 05:02

CraZyDroiD


2 Answers

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

like image 113
Keshan Nageswaran Avatar answered Sep 23 '22 01:09

Keshan Nageswaran


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);
}
like image 28
grizzthedj Avatar answered Sep 24 '22 01:09

grizzthedj