0

So I have the following situation (all are functional components). <Main>, where it returns

<Comp A>
<Comp B>
...
{children}
...

I have a piece of info that I want to use in both <Comp A> and sometimes, {children} - I can do it in <Comp A> and the specific {children} separately, but that seems a bit redundant to me. I'm trying to hit that API once in <Main>, and pass the info to both <Comp A> and {children}.React pass props to children and have followed along several solutions, but I'm having trouble accessing the data passed to children.

The structure of my use case might be important here: I'm trying to access the data in <Other Comp>, which is defined as

<Main>
<div>blablabla</div>
</Main>

And my goal is to say, be able to render whatever is passed in the "blablabla" part of the code. So the <Other Comp> isn't technically a child of Main, but it is filling in the {children} part. Wonder if this is possible at all? Thanks!

Michael Xu
  • 188
  • 3
  • 11
  • 1
    Have you considered using a state managing tool like [Redux](https://redux.js.org/)? That way you can set your data in the store and grab it from different places in your application. This is only a suggestion as I do not know the entire scope of your application. – tomerpacific Feb 08 '20 at 04:49
  • 1
    @tomerpacific I'll check that out! I'm not too familiar with Redux but if this sounds like a good use case for that I am willing to look into it! – Michael Xu Feb 08 '20 at 05:00

1 Answers1

1

I guess Redux would be kinda "overkill" for this case. Using React Context API will be a great option. Just follow these simple steps to create a HOC Context:

1. Create a new file, for example Context.js

/* Context.js */ 
import React, { createContext } from "react"

export const InfoContext = createContext()

// HOC Component
const MyContextProvider = ({ children }) => {
  // define your 'info' value (you can define many values)
  const info = "your info"

  return (
    <InfoContext.Provider
      value={{
        info
      }}
    >
      {children}
    </InfoContext.Provider>
  )
}

export default MyContextProvider 

2. Wrap your components or (<Main> if you like) with this HOC MyContextProvider

<MyContextProvider>
   ...
   <Comp A>
   <Comp B>
   ...
</MyContextProvider>

3. Now, you can access info value anywhere in <Comp A> | <Comp B> with useContext Hook like this:

import React, { useContext } from "react"
import { InfoContext } from "../Context"

const CompA = () => {
  const { info } = useContext(InfoContext)

  return <h1>{info}</h1>
}

export default CompA

Edit react useContext hook

awran5
  • 4,333
  • 2
  • 15
  • 32