the BrowserRouter
component is just a context provider! you can wrap it around your root component to have access to the "route context" everywhere.
the Link
component enables navigation. it takes a to
prop (string) to indicate the path to navigate to.
the Switch
component is basically a switch-statement. you can put Route
components inside them, each with its own path
prop and render
prop.
the route matcher matches based on prefix, so you should use a regular expression (e.g. path="/^"
) or provide exact
to the component to match an exact path.
rather than a render
prop, you can also provide React children.
example with Link
, Switch
and Route
:
import React from "react"
import {Link, Switch, Route} from "react-router-dom"
import Home from "./Home"
import About from "./About"
function App() {
return (
<div>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Switch>
<Route exact path="/"> {/* or path="/^" (regex) */}
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</div>
)
}
export default App