How to Route without reloading the whole page?
for the most recent release (v2.0.0-rc5
), the recommended navigation method is by directly pushing onto the history singleton.
DEMO
Relevant code
import { browserHistory } from './react-router'
browserHistory.push('/some/path')
If using the newer react-router API, you need to make use of the history
from this.props
when inside of components so:
static propTypes = {
history: React.PropTypes.object
}
this.props.history.push('/some/path');
If using react-router-redux
, it offers a push
function you can dispatch like so:
import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));
In v2.4.0 and above, use a higher order component to get the router as a prop of your component.
import { withRouter } from 'react-router'
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
var DecoratedExample = withRouter(Example);
// PropTypes
Example.propTypes = {
router: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
}).isRequired
};
Visit this link for more information: http://kechengpuzi.com/q/s31079081
React >= 16.8 and react-router v4
No one mentioned a solution for an app using hooks. Since React 16.8 (and react-router 4, not sure what is the minimal version, I use the latest), you can use a hook called useHistory.
import { useHistory } from 'react-router';
const MyHookComponent: React.FC = () => {
const routerHistory = useHistory();
routerHistory.push('/page-where-to-redirect');
return <></>;
}
export default MyHookComponent;
More info here https://reactrouter.com/web/api/Hooks/.
Update: react-router v6
There was a new hook introduced in react-router 6:
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate('/page-where-to-redirect');
Documentation can be be found here https://reactrouterdotcom.fly.dev/docs/en/v6/api#usenavigate
This is the only thing that worked for me:
window.history.pushState("", "", "/new-url");
OR to replace:
window.history.replaceState("", "", "/new-url");
Import th Link component first :
import { Link } from 'react-router-dom'
instead of :
<Route path="landing" component={Landing} />
use :
<Link to="landing" />