Home > AI > Frontend > react-router-dom >

withRouter

This is a high order component and will provide the component not wrapped in the Route with three props: match, location, and history.

Example: https://codesandbox.io/s/react-router-withrouter-forked-4isp3

index.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import About from "./components/About";
import Home from "./components/Home";
import Topics from "./components/Topics";
import Nav from "./components/Nav";

const BasicExample = (props) =>
  <Router>
    <div>
      <Nav/>
      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>;

render(<BasicExample />, document.getElementById("root"));

About.js / Home.js

import React from 'react';

const About = () => (
  <div>
    <h2>About</h2>
  </div>
);

export default About;

import React from 'react';



const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
);

export default Home;


Nav.js (just wrap with withRouter)

import React from "react";
import { Link, withRouter } from "react-router-dom";

const Nav = (props) => (
  <ul>
    <li>
      <Link to="/">Home</Link>
    </li>
    <li>
      <Link to="/about">About</Link>
    </li>
    <li>
      <Link to="/topics">Topics</Link>
    </li>
    <li>{`match prop -> ${JSON.stringify(props.match)}`}</li>
    <li>{`location prop -> ${JSON.stringify(props.location)}`}</li>
  </ul>
);

export default withRouter(Nav);

Topics.js (this shows how to render post very good)

import React from "react";
import { Link, Route } from "react-router-dom";

const Topic = ({ match, location }) => (
  <div>
    <h3>{match.params.topicId}</h3>
    <li>{`match prop -> ${JSON.stringify(match)}`}</li>
    <li>{`location prop -> ${JSON.stringify(location)}`}</li>
  </div>
);

const Topics = ({ match, location, history }) => (
  <div>
    <h2>Topics</h2>
    <li>{`match prop -> ${JSON.stringify(match)}`}</li>
    <li>{`location prop -> ${JSON.stringify(location)}`}</li>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>Rendering with React</Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>Components</Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic} />
    {/* <Route
      exact
      path={match.url}
      render={() => <h3>Please select a topic.</h3>}
    /> */}
  </div>
);

export default Topics;

Leave a Reply