← Go Back

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>
)
view raw Basic with div.js hosted with ❤ by GitHub

View this gist on GitHub

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>
);

View this gist on GitHub

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>
);
}
view raw function Basic.js hosted with ❤ by GitHub

View this gist on GitHub

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

SandBoxhttps://codesandbox.io/s/r4nlpx3j5o

Examples on Downshift repository