Programmatically Navigate using react-router

Asked
Active3 hr before
Viewed126 times

9 Answers

programmaticallyrouterreactusing
90%

Programmatically navigate in class-based components.,import { withRouter } from 'react-router-dom',You can use the new useHistory hook on Functional Components and Programmatically navigate:

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

The withRouter higher-order component will inject the history object as a prop of the component. This allows you to access the push and replace methods without having to deal with the context.

import { withRouter } from 'react-router-dom'
// this also works with react-router-native

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

The <Route> component isn't just for matching locations. You can render a pathless route and it will always match the current location. The <Route> component passes the same props as withRouter, so you will be able to access the history methods through the history prop.

import { Route } from 'react-router-dom'

const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

The last option is one that you should only use if you feel comfortable working with React's context model (React's Context API is stable as of v16).

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      // context.history.push === history.push
      context.history.push('/new-location')
    }}
  >
    Click Me!
  </button>
)

// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}
load more v
88%

If you want to customise your component rendering output, you need to wrap your component in a function and use the render option, in order to pass to your component any other props you desire, apart from match, location and history. An example to illustrate:

import { BrowserRouter as Router } from 'react-router-dom'

const ButtonToNavigate = ({ title, history }) => (
  <button
    type="button"
    onClick={() => history.push('/my-new-location')}
  >
    {title}
  </button>
);

const SomeComponent = () => (
  <Route path="/" render={(props) => <ButtonToNavigate {...props} title="Navigate elsewhere" />} />
)    

const App = () => (
  <Router>
    <SomeComponent /> // Notice how in v4 we can have any other component interleaved
    <AnotherComponent />
  </Router>
);

This higher order component will inject the same props as Route. However, it carries along the limitation that you can have only 1 HoC per file.

import { withRouter } from 'react-router-dom'

const ButtonToNavigate = ({ history }) => (
  <button
    type="button"
    onClick={() => history.push('/my-new-location')}
  >
    Navigate
  </button>
);


ButtonToNavigate.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
  }),
};

export default withRouter(ButtonToNavigate);

<Redirect to="/your-new-location" push />

const ButtonToNavigate = (props, context) => (
  <button
    type="button"
    onClick={() => context.router.history.push('/my-new-location')}
  >
    Navigate to a new location
  </button>
);

ButtonToNavigate.contextTypes = {
  router: React.PropTypes.shape({
    history: React.PropTypes.object.isRequired,
  }),
};
load more v
72%

The primary way you programmatically navigate using React Router v4+ is by using a <Redirect /> component, and it’s a recommended method that helps the user navigate between routes.,The main focus of this article was to share how you can safely navigate between components using the React Router package.,React Router is designed to follow the ideology as mentioned earlier. Thus, programmatically navigating with React Router should, by definition, align with those three core concepts.

import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { userLogin } from './userAction';
import Form from './Form';
const Login = () => {
 const [isLoggedIn, setIsLoggedIn] = useState(false);
  
 const handleLogin = async (userDetail) => {
  const success = await userLogin(userDetail);
  if(success) setIsLoggedIn(true);
 }
  
  if (isLoggedIn) {
   return <Redirect to='/profile' />
  }
  return (
   <>
    <h1>Login</h1>
    <Form onSubmit={handleLogin} />
   </>
  )
}
export default Login;
load more v
65%

In this post you’ll learn how programmatically navigate with React Router v5+ and the new useHistory hook!,To programmatically navigate means to use JavaScript, i.e. program code, a function or method call. If you just want a straight-up hyperlink then your best bet is <Link to="/some-url" />, otherwise here we go!, Fully understand how to manage JavaScript Data Structures with immutable operations

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import Hello from './Hello';
import Goodbye from './Goodbye';

const App = () => (
  <Router>
    <Route exact path="/" component={Hello} />
    <Route path="/goodbye" component={Goodbye} />
  </Router>
);

render(<App />, document.getElementById('root'));
load more v
75%

The primary way you programmatically navigate using React Router v5 is by using a <Redirect /> component.,Let’s look at an example then we’ll walk through more of why this isn’t as crazy as it may first appear.,🚨 Note this post is using React Router v5. If you’re using another version, find it below

function Register () {
  const [toDashboard, setToDashboard] = React.useState(false)

  if (toDashboard === true) {
    return <Redirect to='/dashboard'/>
  }

  return (
      <div>
        <h1>Register</h1>
        <Form afterSubmit={() => toDashboard(true)} />
      </div>
  )
}
load more v
40%

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

import {
   useHistory
} from "react-router-dom";

function HomeButton() {
   const history = useHistory();

   function handleClick() {
      history.push("/home");
   }
   return ( < button type = "button"
22%

The primary way to do that is by using the <Redirect/>component. The typical way is routing on some kind of user event. Refer the below example.,Another way to do it is by pushing a new history to props.history.,Web Components in Angular.js

class Register extends React.Component {  state = {    toDashboard: false,  }  handleSubmit = (user) => {    saveUser(user)      .then(() => this.setState(() => ({        toDashboard: true      })))  }  render() {    if (this.state.toDashboard === true) {      return <Redirect to='/dashboard' />    }    return (      <div>        <h1>Register</h1>        <Form onSubmit={this.handleSubmit} />      </div>    )  }}
load more v
60%

Using react-router I am able to use a Link element and create links which by default react router handles the navigation for them!,This is a quick one about “react-router”, a problem I faced and the solution I found, so just wanted to share with you!,In React Router version 5.1.0 and after that there is a new useHistory hook (I think that is in React version 16.8.0 and higher) which does this for me!

How? here is a snippet of code that does it:

import { useHistory } from "react-router-dom";function HomeButton() {  const history = useHistory();  function handleClick() {    history.push("/home");  }  return (    <button type="button" onClick={handleClick}>      Go home    </button>  );}
48%

I have seen my fair share of react tutorials, but any time that they talk about navigation using react-router, they only show the way using the Link component. As soon as someone starts working on his/her own project, one of the first problems they come across is how to route programmatically, which basically means routing with ways other than clicking on something wrapped inside a <Link> component. This blog mainly aims to be a refuge to those people who come here looking for the answers to this problem.,As of release 5.1.2, react-router ships with some new hooks that can help us access the state of the router.,A common problem that we can encounter here is that in components which are not an immediate child to the <Route> component, there is no history prop present. This can be easily solved using the withRouter function.

import {
   Redirect
} from "react-router-dom";
load more v

Other "programmatically-router" queries related to "Programmatically Navigate using react-router"