jesuslovesu2baby
jesuslovesu2baby

Reputation: 11

useContext with React Hooks to set state of parent from child

I got a bit of a simple question that I can't seem to resolve no matter how much I've research the docs and similar questions.

This is my app component (parent component)

import React, { createContext, useState } from 'react';
import Search from './search/search.jsx';

export const SearchContext = createContext();

function App() {
    const [keyword, setKeyword] = useState('');

    return (
        <div id='app-main-container'>
            <SearchContext.Provider value = {setKeyword}>
                <Search />
            </SearchContext.Provider>
        </div>
    );
};

export default App;

This is my search component which is utilizing the SearchContext created in the app component

import React, { useContext } from 'react';
import SearchContext from '../app.jsx';

export default function SearchBar(props) {
    const setKeyword = useContext(SearchContext);

    return (
        <div id='search-bar-container'>
            <input onChange={e => setKeyword(e.target.value)}></input>
        </div>
    );
};

What I'm trying to do is essential set the state of keyword in my app component by using the setKeyword function which I'm passing down via the value of the SearchContext.provider and calling during the onChange event. Main reason for doing this is to avoid passing down setKeyword as a prop. What am I missing here? When I do console.log(setKeyword) it returns undefined which means I'm either not passing my argument correctly or I'm accessing it incorrectly.

Upvotes: 0

Views: 2801

Answers (1)

jesuslovesu2baby
jesuslovesu2baby

Reputation: 11

import { SearchContext } from '../app.jsx';

Forgot to destructure the key out

Upvotes: 1

Related Questions