-1

I am trying to update parent components title from child components url. But the child components are loaded as navigation

Here is my Sandbox

https://codesandbox.io/s/react-typescript-forked-z1ijxi

Here is my layout.tsx

import { createContext, useContext, useState } from "react";
import { Outlet, Link } from "react-router-dom";

const Layout = () => {
  const title = "";

  return (
    <>
      <h2>{title}</h2>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/blogs">Blogs</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>

      <Outlet />
    </>
  );
};

export default Layout;

Here I need to change the {title} when each of the child component loads

I tried to follow this answer . But I was not able to accomplish that.. Sorry very new in React

Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132
  • These `link` will change the route and will display relevant component. In this case what is the significance of changing the value of `title` when the component itself isn't present. – Mohammed Shahed Dec 20 '22 at 16:31
  • Didnt understand your point. The layout component will stay there when a component being loaded into the Outlet. Sorry if I misunderstood react routing flow. – Sandeep Thomas Dec 20 '22 at 17:01
  • What is/was unclear with the [answer](https://stackoverflow.com/questions/70655186/is-it-possible-to-use-multiple-outlets-in-a-component-in-react-router-v6/70655615#70655615) you are referencing? It's my answer so I'm totally happy to help clear anything up. From what I see of your code snippet and sandbox code the `title` needs to be React state in the `Layout` and the `Outlet` needs to provide a context value passing down a callback for nested routes to update the state. – Drew Reese Dec 20 '22 at 17:42
  • This also seems to be a duplicate of your other [question](https://stackoverflow.com/q/74854171/8690857). Do you need a *running* code example using Typescript in the answer I've provided there? – Drew Reese Dec 20 '22 at 17:46
  • @DrewReese Yes boss.. THanks a lot for that.. I made it as a separate question to add more details with the sandbox part.. Unfortunately I ve got stuck with its implementation in typescript.. Could you please help me on that sandbox sample – Sandeep Thomas Dec 21 '22 at 08:42

1 Answers1

0

I would recommend using React Redux in your project. This library adds a variable namespace that is available to every component. From this global namespace, you could define a title variable that is accessible to the Layout component and editable by any other component no matter where it is.

Redux takes some time to learn, but it's very useful in all kinds of projects. This article has more information on the concept of Redux, though the exact implementation is a little outdated.