How to use Redirect in the new react-router-dom of Reactjs How to use Redirect in the new react-router-dom of Reactjs javascript javascript

How to use Redirect in the new react-router-dom of Reactjs


You have to use setState to set a property that will render the <Redirect> inside your render() method.

E.g.

class MyComponent extends React.Component {  state = {    redirect: false  }  handleSubmit () {    axios.post(/**/)      .then(() => this.setState({ redirect: true }));  }  render () {    const { redirect } = this.state;     if (redirect) {       return <Redirect to='/somewhere'/>;     }     return <RenderYourForm/>;}

You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow


That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.

But I guess you have your reasons to do it this way.


Here a small example as response to the title as all mentioned examples are complicated in my opinion as well as the official one.

You should know how to transpile es2015 as well as make your server able to handle the redirect. Here is a snippet for express. More info related to this can be found here.

Make sure to put this below all other routes.

const app = express();app.use(express.static('distApp'));/** * Enable routing with React. */app.get('*', (req, res) => {  res.sendFile(path.resolve('distApp', 'index.html'));});

This is the .jsx file. Notice how the longest path comes first and get's more general. For the most general routes use the exact attribute.

// Relative importsimport React from 'react';import ReactDOM from 'react-dom';import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';// Absolute importsimport YourReactComp from './YourReactComp.jsx';const root = document.getElementById('root');const MainPage= () => (  <div>Main Page</div>);const EditPage= () => (  <div>Edit Page</div>);const NoMatch = () => (  <p>No Match</p>);const RoutedApp = () => (  <BrowserRouter >    <Switch>      <Route path="/items/:id" component={EditPage} />      <Route exact path="/items" component={MainPage} />                <Route path="/yourReactComp" component={YourReactComp} />      <Route exact path="/" render={() => (<Redirect to="/items" />)} />                <Route path="*" component={NoMatch} />              </Switch>  </BrowserRouter>);ReactDOM.render(<RoutedApp />, root); 


React Router v5 now allows you to simply redirect using history.push() thanks to the useHistory() hook:

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