In React Router, the match
, location
, and history
objects are passed as props to the component rendered by a <Route>
component. These objects provide information about the current route and allow you to perform navigation.
match
: Thematch
object contains information about how the current route matches the URL. It contains properties such asparams
,path
,url
, etc. Here’s an example of how to use thematch
object to access dynamic parts of the URL:
import { BrowserRouter as Router, Route } from 'react-router-dom'
function User({ match }) {
return <h1>Welcome {match.params.username}</h1>;
}
function App() {
return (
<Router>
<Route path="/users/:username" component={User} />
</Router>
);
}
In this example, we have a route that matches URLs of the form /users/:username
, where :username
is a dynamic part of the URL. We are using the match
object to access the value of :username
in the User
component and display a welcome message.
location
: Thelocation
object contains information about the current URL and the state of the browser. It contains properties such aspathname
,search
,hash
,state
, etc. Here’s an example of how to use thelocation
object to display the current URL:
import { BrowserRouter as Router, Route } from 'react-router-dom'
function Location({ location }) {
return <h1>You are currently on: {location.pathname}</h1>;
}
function App() {
return (
<Router>
<Route path="/" component={Location} />
</Router>
);
}
In this example, we have a route that matches the root path /
, we are using the location
object to access the pathname
property and display the current URL in the Location
component.
history
: Thehistory
object contains methods that allow you to navigate between routes. It contains methods such aspush
,replace
,go
,goBack
,goForward
, etc. Here’s an example of how to use thehistory
object to navigate to a different route:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
function About({ history }) {
return (
<div>
<h1>About</h1>
<button onClick={() => history.push('/')}>Go to Home</button>
</div>
);
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Router>
);
}
In this example, we have a route that matches the path /about
, we are using the history
object to access the push
method in the About
component,