Home > Blockchain >  Change parent component variable from child component when using routing in react
Change parent component variable from child component when using routing in react

Time:12-21

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

CodePudding user response:

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.

CodePudding user response:

You can use event emitter to solve this problem here is the brief description of how it works https://checklistgurus.com/checklist-request/d428fa8b-2361-4c31-8221-7a5d7f713bcc

here is the modified code you can use https://codesandbox.io/s/react-typescript-forked-c4sthh?file=/src/pages/Layout.tsx:292-459

  • Related