📜  react touter dom - Javascript(1)

📅  最后修改于: 2023-12-03 14:46:58.307000             🧑  作者: Mango

React Router DOM - Javascript

React Router DOM is a popular library used by Javascript developers to handle routing and navigation in their web applications. This library provides a declarative way to route the components of the application based on the URL.

Getting Started

To start using React Router DOM, first we need to install it using npm or yarn:

npm install react-router-dom
yarn add react-router-dom

Once installed, we can import the required components from the library:

import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
Router

The Router component is the top-level component. We need to wrap all the app components inside this component:

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/contact">
            <Contact />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}
Route

The Route component is used to define the path and the component to be rendered when the URL of the application matches the defined path. The prop path is used to define the URL path to match, and the prop component is used to define the component to render:

function Home() {
  return <h3>Home</h3>;
}
function About() {
  return <h3>About</h3>;
}
function Contact() {
  return <h3>Contact</h3>;
}

<Switch>
  <Route path="/about">
    <About />
  </Route>
  <Route path="/contact">
    <Contact />
  </Route>
  <Route path="/">
    <Home />
  </Route>
</Switch>
Link

The Link component is used to provide a clickable link to navigate between different pages in the application. The prop to is used to define the target URL:

<div>
  <nav>
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/about">About</Link>
      </li>
      <li>
        <Link to="/contact">Contact</Link>
      </li>
    </ul>
  </nav>

  <Switch>
    <Route path="/about">
      <About />
    </Route>
    <Route path="/contact">
      <Contact />
    </Route>
    <Route path="/">
      <Home />
    </Route>
  </Switch>
</div>
Conclusion

React Router DOM is a powerful library that helps in building complex web applications by handling routing and navigation with ease. With its declarative approach, it provides a simple and intuitive way to manage components based on the URL path.