Search code examples
reactjsreact-propsuse-context

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); };


Solution

  • 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);