简体   繁体   中英

Does react-router-dom automatically pass history object to children components inside Router?

This will probably be a rookie question but does Router component passes down the history object to child components automatically? to demonstrate I have this

App.js;


const App = () => {
  return (
    <>
      <h1>Hello</h1>
      <Router history={history}>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/another_route" exact component={AnotherRoute} />
        </Switch>
      </Router>
    </>
  );
};


and Home and Another Route components taking advantage of the history prop to re-route without explicitly being passed down to the children via Router.


// Home.js

import React from "react";

const Home = (props) => {
  return (
    <>
      <h3> Hello From home </h3>
      <button onClick={() => props.history.push("/another_route")}>
        click here to go another route
      </button>
    </>
  );
};

export default Home;


// AnotherRoute.js

import React from "react";

const AnotherRoute = (props) => {
  return (
    <>
      <h3> Hello From this another Route </h3>
      <button onClick={() => props.history.push("/")}>
        click here to go back
      </button>
    </>
  );
};

export default AnotherRoute;

Everything functioning just fine, but I would like to understand this. I haven't seen it in the documentation explicitly.

here is a codesandbox I created for you to experiment:

https://codesandbox.io/s/react-router-dom-passes-history-object-to-children-automatically-jj7ih

thanks.

Yes All Route render methods will be passed the same three route props, match , location , history . So you can use these props in all the components you render with react-router-dom

What are Route render methods?

The recommended method of rendering something with a <Route> is to use children elements. There are, however, a few other methods you can use to render something with a <Route> like

<Route component>
<Route render>
<Route children> function

What is your Route render method in your example?

You have used <Route component> as <Route path="/" exact component={Home} />

Official Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM