8bitzz / blogs

0 stars 0 forks source link

ReactJS Callback Handler & Lifting State #3

Open 8bitzz opened 3 years ago

8bitzz commented 3 years ago

Lifting State

Callback Handler

React props are always passed down as information the component tree, and callback handlers passed as functions in props can be used to communicate up the component hierarchy

Example

const App = () => {
    const [searchTerm, setSearchTerm] = React.useState('');

    // A - Pass function handleSearch() from parent component (BlogFeed) to children component (BlogSearch)
    const handleSearch = event => {
        // C - Actual implementation of function handleSearch() is in parent component (BlogFeed)
        setSearchTerm(event.target.value);
    }

    return (
        <BlogFeedWrap>
            <h1>Blogs</h1>
            <BlogSearch onSearch={handleSearch}/>
            <BlogList list={blogs} />
        </BlogFeedWrap>
    );
}
const BlogSearch = props => {
    return (
        <BlogSearchWrap>
                {/* B - Call function handleSearch() from children component (BlogSearch) as soon as input change via props */}
                <SearchInput type='text' onChange={props.onSearch}></SearchInput>
                <Button size='small'>Search</Button>
        </BlogSearchWrap>
    );
}