0

This is what my code looks like:

Context.js:

const Context = createContext();
export default Context;

ContextProvider.js:

import Context from './Context';
const ContextProvider = () =>
{
   ....
   return(<Context.Provider value={data: 1}>{props.children}</Context.Provider>
}

ParentClass.js:

const ParentClass = () => 
{
   ...
   return(
      <div>
       ...
      {boolValue ? (
      <ContextProvider>
         <ConsumerComponent/>
      </ContextProvider>) 
      </div>)
}

ConsumerComponent.js:

import Context from './Context.js';
const ConsumerComponent = () => {
   const contextData = useContext(Context);
   ...
}

My issue is that ConsumerComponent doesn't seem to be able to access context data; it doesn't render at all when I add the const contextData = useContext(Context); line, and nothing gets logged when I try to print contextData. Where exactly did I go wrong? From my understanding, I followed the necessary steps of creating context + a provider, making sure that the consuming component has a provider as one of its ancestor components, and then accessing the context with useContext().

1

1 Answer 1

1

Considering you want the value prop of the Context Provider to be an object like

{ data : 1 }

you probably forgot the extra curly braces, because the first pair is the JSX syntax to interpret the content as JavaScript instead of a string.

So your value prop on ContextProvider.js file probably should look like this:

<Context.Provider value={{data: 1}}>{props.children}</Context.Provider>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.