Downshift getRootProps
Broken Post? → Let me know
Photo by Tim Carey on Unsplash
Self note while learning Downshift by Kent C. Dodds.
Downshift requires you to have div
as the root element.
export default () => ( | |
<Downshift | |
onChange={selection => alert(`You selected ${selection.value}`)} | |
itemToString={item => (item ? item.value : '')} | |
> | |
{downshift => ( | |
<div> | |
... | |
</div> | |
)} | |
</Downshift> | |
) |
When Downshift's child is not a div
(to extract the functionality into a different component) then getRootProps should be called.
const DownshiftContext = React.createContext(); | |
export default () => ( | |
<Downshift | |
onChange={selection => alert(`You selected ${selection.value}`)} | |
itemToString={item => (item ? item.value : "")} | |
> | |
{downshift => ( | |
<DownshiftContext.Provider value={downshift}> | |
<h2>Basic Example</h2> | |
<div> | |
<Basic {...downshift.getRootProps({ refKey: "innerRef" })} /> | |
</div> | |
</DownshiftContext.Provider> | |
)} | |
</Downshift> | |
); |
And make sure to set the inner component's root element ref
to the refKey
assigned in getRootProps
.
function Basic({ innerRef }) { | |
... | |
return ( | |
<div ref={innerRef}> | |
... | |
</div> | |
); | |
} |
CodeSandbox 🐛?
For some reason, CodeSandbox shows the following error message.
downshift: You must apply the ref prop "innerRef" from getRootProps onto your root element.
says CodeSandbox
But when deployed on Netlify, no error message occurs as shown below.
No getRootProps error message
Resources
SandBox - https://codesandbox.io/s/r4nlpx3j5o
Examples on Downshift repository
Webmentions
Loading counts...
❤️ 0 💬 0
Fetching Replies...
There is no reply...