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';
}
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:
<a>
as your button<button>
and redirect programaticallySince 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
window.location
is not properly called in render methodwindow.location.assign()
method which helps to load new document JSX
pages are rendered directly in browser level when you try to call them directlyHope 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With