CraZyDroiD
CraZyDroiD

Reputation: 7127

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';
}

Upvotes: 7

Views: 64049

Answers (3)

grizzthedj
grizzthedj

Reputation: 7505

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);
}

Upvotes: 6

Keshan Nageswaran
Keshan Nageswaran

Reputation: 8188

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

Upvotes: 18

Tumen_t
Tumen_t

Reputation: 801

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>

Upvotes: 1

Related Questions