Reputation: 1962
I am looking for a way to change routes in reactJS using react-router
when a user clicks a button.
Here is the relevant code (details of components have been omitted for brevity) from my jsx
file:
var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory, browserHistory} = require('react-router');
var {Link, IndexLink} = require('react-router');
var Main = React.createClass({
render: function(){
return(
<div>
<header>
<Router history={hashHistory}>
<Route path='/' component={Splash}></Route>
<Route path='login' component={Login}/>
</Router>
</header>
<footer>
<Button_/>
</footer>
</div>
);
}
});
var Login = React.createClass({
render: function(){
return(
<div>This is the login component</div>
);
}
});
var Button_ = React.createClass({
handleClick: function(e){
e.preventDefault();
},
render: function(){
return(
<Link to='/login' activeClassName='active'>LOGIN</Link>
);
}
});
var Splash = React.createClass({
render: function(){
return(
<div>This is the Splash component</div>
);
}
});
ReactDOM.render(<Main/>, document.getElementById('app'));
As you can probably see by now, the Splash
component is the default one shown on the page. When the user clicks the Link
in the Button_
component, I want the Splash
component to be replaced with the Login
component in the DOM.
I'm running a python server to test, so the URL looks like http://localhost:8000/public/#/?_k=hqkhl0
The code I have currently doesn't do what I want it to do. If I manually type in http://localhost:8000/public/#/login
, the page changes, but clicking the button doesn't work.
I also tried manually changing the page by using browserHistory.push()
within the 'handleClick' function of 'Button_' (and also added the onClick
property in the correct place), however this didn't give me the results I wanted.
I first tried
browserHistory.push('/#/login');
This resulted in a redirect to http://localhost:8000/#/login
, obviously not right.
I then tried
browserHistory.push('public/#/login');
which resulted in a redirect to http://localhost:8000/public/public/#/login
, again, incorrect.
How can I successful route to the Login
component?
Upvotes: 2
Views: 6995
Reputation: 129
import {useHistory} from 'react-router-dom'
const history=useHistory()
handleClick=()={
history.push('/path')
}
RRD provide us useHistory hook with help of which we can access history object of our browser and history.push('/path') method push the browser url to the url we passed it inside barckets.
Upvotes: 1
Reputation: 3548
In your handleClick function just try this:
this.props.router.replace('login')
this is with "react-router": "^3.0.2",
Upvotes: 1
Reputation: 1298
You could try implementing the login route as a child route of the splash route, which could mitigate the problem of going to the wrong level, so to speak.
<Router history={hashHistory}>
<Route path='/' component={Splash}>
<Route path='/login' component={Login}/>
</Route>
</Router>
Upvotes: 0