React Redirect Route: Step-by-Step Guide

In React, routing redirection to a single page can be achieved using the component or programmatically navigating.

  1. Please forward the call.
import { Redirect } from 'react-router-dom';

function App() {
  return (
    <div>
      {/* 定义路由 */}
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        {/* 定义重定向 */}
        <Redirect to="/" />
      </Switch>
    </div>
  );
}

In the example above, users will be redirected to ‘/’ if they visit any path other than ‘/’ and ‘/about’.

  1. Utilize programmatic navigation:
import { useHistory } from 'react-router-dom';

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

  // 在需要重定向的地方调用以下代码
  history.push('/');

  return (
    <div>
      {/* 定义路由 */}
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </div>
  );
}

In the above example, you can redirect the page to ‘/’ by calling the history.push(‘/’) method.

Redirecting to a single page is achieved by defining routes and triggering the redirection under specific conditions, regardless of the method used.

bannerAds