1

I have a main layout for my app and all components are rendered inside it, but this main layout needs to access a variable PageTitle from it's child components, I have looked in react documentation and come up with React Context, but I could'nt figure out how to use it in this case, sorry I am new to React.

Every component rendered by routes has a variable called PageTitle, the MainLayout should use this variable to render current page title on the top of the app, these are all functional components.

<MainLayout>
    <Route path='/' exact component={HomePage} />
    <Route path='/invoice' exact component={Invoice} />
</MainLayout>

Update: I can create a context and store the value like this, but I couldn't figure out how to change it in child components.

Also I think this is a bit overkill, and there should a better solution.

export const AppContext = React.createContext({ PageTitle: 'Home' });

<AppContext.Consumer>{value=>value.PageTitle}</AppContext.Consumer>
esnezz
  • 619
  • 1
  • 7
  • 19
  • 1
    @jmargolisvt I think it's the opposite problem. The author wants to get the data from 'children', not pass it down to children. I guess you can pass a callback down to children and call it within children to notify the parent. but seems a bit too much for it – dance2die Aug 28 '19 at 15:58
  • @MahendraPratap I think passing down the callback works. I will also reply with `context api` workaround, which I think would work better for his case (without prop drilling) – dance2die Aug 28 '19 at 16:00
  • Too late, it's closed... – dance2die Aug 28 '19 at 16:02
  • Ok, I voted to re-open. But I think the issue here is that the OP is generally confused about passing props. I think the "dupe" points them to better arch. The children really shouldn't have to pass the var back up. If they really do, the answer is context or redux both of which are extensively documented. – jmargolisvt Aug 28 '19 at 16:19
  • This is not a duplicate question, please at least read it clearly before marking it as duplicate – esnezz Aug 28 '19 at 16:21

0 Answers0