How to set dynamic Title in NavBar

Viewed 83

I'm using Navbar as the root file and I have 3 pages(profile, About, and Home), I want to get data from pages to the root file, e.g. (title = "Profile"), because I want to display the title in the navbar.

my navbar page is listed below

import React from "react";

function app(){
return(
<div className="topnav">
          <a
            style={{
              fontWeight: "bold",
              fontSize: "20px",
              position: "absolute",
              margin: "10px",
              color: "#001b2b",
            }}
          >
            {title}
          </a>
<Link exact to="/profile">profile</Link>
<Link exact to="/home">Home</Link>
<Link exact to="/about">About</Link>

</div>
)}

if I click profile I want to set the title="profile"

I stuck to get data from child component

2 Answers

Since its just a title, rather than sending values from child to parent, you can just set a session variable PageTitle when you are clicking on any of the menu on navigation bar and refresh the state. If you are in Profile page the set session variable as below

import { ReactSession }  from 'react-client-session';
ReactSession.set("PageTitle", "Profile");

and in your root file you can get this session variable as below,

this.title = ReactSession.get("PageTitle");  // This will Return "Profile"

you can use useState hook to get the page that you gonna to go in, and after that you can update your title.

import React from "react";

function app(){
const [title, setTitle] = React.useState('');
return(
<div className="topnav">
          <a
            style={{
              fontWeight: "bold",
              fontSize: "20px",
              position: "absolute",
              margin: "10px",
              color: "#001b2b",
            }}
          >
            {title}
          </a>
<button onClick={()=>setTitle("Profile")}>
<Link exact to="/profile">profile</Link>
</button>
<button onClick={()=>setTitle("Home")}>
<Link exact to="/home">Home</Link>
</button>
<button onClick={()=>setTitle("About")}>
<Link exact to="/about">About</Link>
</button>
</div>
)}

Hope it solve your problem

Related