0

I want to implement context API for transmitting a value in my files.

I have the following folder structure

Screen 
  |-------Search Component
  |-------Container Component

If I set up the context API provider in my Search can I "consume" it in Container using nested component structure. Any help is highly appreciated.

I am implementing the context api for the first time so I am not very clear with all the implementation structure.

Thanks

Tanu
  • 1,286
  • 4
  • 16
  • 35
  • The context api provider becomes its own higher order component. You can wrap both `Search` and `Container` in it and pass it's values and functions down to them as props. – Max Baldwin Jun 13 '19 at 17:58
  • @MaxBaldwin the value I want is in Search Component. That is the limitation I have. Thanks. I am extracting the value using GraphQL query and that is being done in the Search Component. – Tanu Jun 13 '19 at 17:59
  • If it's just being passed down one level, you should just pass it down as a prop to `Container`. If the value is gonna go down multiple levels and some components in the middle wont need that value, use context. – Max Baldwin Jun 13 '19 at 18:00
  • @MaxBaldwin can I achieve the value from search to container using context api. I am specifically asked to try it using nested components approach and it is not working as expected, which makes me think it does not align with nested structure. Am I understanding it correctly. Moreover, the value needs to be passed down child containers present in Container Component so we thought to approach it using context api as we do not need it at multiple places. Thanks – Tanu Jun 13 '19 at 18:04
  • 2
    Then create a `SearchContext` component that is responsible for handling and distributing this value. Then just use your current `Search` component as a view. You can then pass a function via the `SearchContext` component that would allow other components to call that function. – Max Baldwin Jun 13 '19 at 18:07
  • @MaxBaldwin I created my context and provider in the screenComponent and used consumer to update the value in SearchContext and also used consumer to extract and use the value in Container Component and it seems to work as expected. Kindly let me know incase you feel anything wrong with the approach. Thanks – Tanu Jun 14 '19 at 14:58
  • 1
    Sounds good to me!!! – Max Baldwin Jun 14 '19 at 15:19

0 Answers0