2018-11-06
Downshift getRootProps
react, selfnote, downshift
react, selfnote, downshift
_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> | |
); | |
} |
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
SandBox - https://codesandbox.io/s/r4nlpx3j5o
Examples on Downshift repository