How do you configure routing in React?

There are various methods of configuring React routes, but the commonly used ones are:

  1. Wrap the entire application using the BrowserRouter or HashRouter component provided by the react-router-dom package, and configure the routing rules inside it. For example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </Router>
  );
}
  1. Establish routing rules by nesting the Route component provided by the react-router-dom package. For example:
import { Route } from 'react-router-dom';

function App() {
  return (
    <>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </>
  );
}
  1. Wrap the component that needs to access routing information with the higher-order component withRouter provided by the react-router-dom package. For example:
import { withRouter } from 'react-router-dom';

function MyComponent(props) {
  // 可以通过 props 获取路由信息,如 props.history, props.location, props.match
  return <div>Hello React Router!</div>;
}

export default withRouter(MyComponent);

All of the methods above utilize components or higher-order components provided by the react-router-dom package to configure routing rules and obtain route information. The specific method to use can be chosen based on project requirements and personal preferences.

bannerAds