Last active
September 8, 2019 14:00
-
-
Save ryancharris/23bbd5004556c3a7023e1b9a4f3e11aa to your computer and use it in GitHub Desktop.
LogRocket: Context and refs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Applying a ref directly to an HTML element | |
<input | |
className="AuthorFilterMenu__filter-input" | |
ref={authorFilterInputRef} | |
placeholder="Filter by author..." | |
value={filterInputValue} | |
type="search" | |
onInput={event => { | |
setFilterInputValue(event.currentTarget.value); | |
}} | |
/> | |
// Applying a ref to a React component instance | |
<AuthorFilterMenu ref={authorFilterInputRef} /> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Provide value in App.jsx | |
<section className="App__search"> | |
<SearchContext.Provider | |
value={{ | |
openMenu: openMenu, | |
toggleOpenMenu: toggleOpenMenu, | |
addAuthor: addAuthor, | |
addYear: addYear, | |
selectedAuthors: selectedAuthors, | |
selectedYears: selectedYears, | |
authorFilterInputRef: authorFilterInputRef, | |
searchBarRef: searchBarRef, | |
yearFilterInputRef: yearFilterInputRef | |
}} | |
> | |
<SearchBar /> | |
</SearchContext.Provider> | |
</section> | |
// In AuthorFilterMenu.jsx, we grab the ref from the searchContext | |
function AuthorFilterMenu(props) { | |
const contextValue = React.useContext(SearchContext); | |
const { | |
addAuthor, | |
openMenu, | |
selectedAuthors, | |
authorFilterInputRef | |
} = contextValue; | |
} | |
// And then we apply it to the <input> | |
return ( | |
<div className={menuCn}> | |
<input | |
className="AuthorFilterMenu__filter-input" | |
ref={authorFilterInputRef} | |
placeholder="Filter by author..." | |
value={filterInputValue} | |
type="search" | |
onInput={event => { | |
setFilterInputValue(event.currentTarget.value); | |
}} | |
/> | |
<ul className="AuthorFilterMenu__list">{createMenuItems()}</ul> | |
</div> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment