简体   繁体   中英

React.Js Passing props from component to NavBar component?

So I have React.JS page and this page is made out of two parts. The NavBar and the page content.

In the App.js I am passing props to the page and I want to display this props in the NavBar as Page title. How can I do this?, basicaly every link has it own props, which is the name of the page and I wouls like to display this props in the PageHeader component.

import {BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Banany from "./Banany";
import Broskve from "./Broskve";
import PageHeader from "./Components/PageHeader";
import Home from "./Home";
import Hrusky from "./Hrusky";


function App() {
  return (
    <Router>
      <PageHeader/>

      <Switch>
        <Route exact path="/">
          <Home pageTitle="Home"/>
        </Route>
        <Route path="/banany">
          <Banany pageTitle="Bananas"/> <--- I want to display Bananas in PageHeader component
        </Route>
        <Route path="/broskve">
          <Broskve pageTitle="Broskve"/>
        </Route>
        <Route path="/hrusky">
          <Hrusky pageTitle="Pears"/>
        </Route>
      </Switch>

    </Router>
  );
}

export default App;

There are all kinds of methods of doing this.
2 most relevant that come to mind:

  • Give every route a param, ie pageTitle , just like you pass to every comp.
    Then you can access it from the navbar.
  • Manage a global state, either with a specialized library (redux/etc..), or simply with React's built-in contextAPI.

In this case, I would go with the first method as it is simpler if that's all you need.

If the Page Header depends on your route just move it inside your Route like so:

<Route path="/banany">
  <PageHeader pageTitle="Bananas" />
  <Banany pageTitle="Bananas" />
</Route>

Obviously there are other ways to achieve this behavior and it might be repetitiv but this is the straight forward approach.

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