Search code examples
htmlreactjsreact-hooksreact-routerreact-props

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;

Solution

  • 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.