Filip Studený
Filip Studený

Reputation: 622

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;

Upvotes: 0

Views: 797

Answers (2)

giggo1604
giggo1604

Reputation: 511

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.

Upvotes: 1

tomleb
tomleb

Reputation: 2525

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

  • Give every route a param, i.e. 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.

Upvotes: 1

Related Questions