Blogs Technology

Give me realtime example of using match, location and history

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.

  1. match: The match object contains information about how the current route matches the URL. It contains properties such as params, path, url, etc. Here’s an example of how to use the match 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.

  1. location: The location object contains information about the current URL and the state of the browser. It contains properties such as pathname, search, hash, state, etc. Here’s an example of how to use the location 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.

  1. history: The history object contains methods that allow you to navigate between routes. It contains methods such as push, replace, go, goBack, goForward, etc. Here’s an example of how to use the history 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,

Leave a Reply

Your email address will not be published. Required fields are marked *