How to go to another onClick in react page

I am new to react and I try to load another page when the user clicks a button. I used window.location but nothing happens when I click the button. How to fix it?

This is where I enabled 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';
}
+6
source share
3 answers

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

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

, React Router. Javascript:

:

  • <a>
  • <button>

, - React router. button

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

,

  • , window.location,
  • window.location.assign(),
  • , JSX , .

, , , , ,

+2

You need to access the method with this, otherwise React will not find it.

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

Source: https://habr.com/ru/post/1015112/


All Articles