Simon
Simon

Reputation: 63

How to set props into const X = useContext()

Using ReactJS

I am wondering, how I can pass props into const { answerSetter } = useContext( AnswerSetterContext ); The reason I want to do this is beacause I get error, that X is not a function and passsing props there should fix it. My code: export const AnswerSetterContext = createContext(null);

<AnswerSetterContext.Provider value={answerSetter}>
         <SearchBar key="SearchBar" placeholder="Type something" data={data} />
      </AnswerSetterContext.Provider> 

const { answerSetter } = useContext(AnswerSetterContext);

const handleOptionClick = event => {
    const selectedValue = event.target.value;

answerSetter is not a function ==> answerSetter(selectedValue); };

Upvotes: 0

Views: 61

Answers (1)

Irfanullah Jan
Irfanullah Jan

Reputation: 3892

You need to pass an object into AnswerSetterContext.Provider (please notice the extra pair of curly brackets {} around answerSetter when I pass it into value prop):

<AnswerSetterContext.Provider value={{answerSetter}}>
    <SearchBar key="SearchBar" placeholder="Type something" data={data} />
</AnswerSetterContext.Provider> 

const { answerSetter } = useContext(AnswerSetterContext);

Upvotes: 1

Related Questions