@formoe/use-selection
v2.1.0
Published
The `useSelection` hook encapsulate the common use case of selecting something inside a component but needing the selected value outside.
Downloads
127
Keywords
Readme
use-selection
The useSelection
hook encapsulate the common use case of selecting something inside a component but needing the selected value outside.
First you wrap a context provider with the selectable options around the component you need the selected value in, then you can use the useSelection()
hook deeper in the tree to render the options and select an item.
Example
import { useSelection, SelectionProvider } from "@formoe/use-selection"
const SelectionComponent = () => {
const { options, selectItem } = useSelection()
return (
<>
{options.map((item) => (
<button onClick={() => selectItem(item)} key={item.id}>
Select: {item.id} - {item.name}
</button>
))}
</>
)
}
const DisplayComponent = () => {
const { selectedItem } = useSelection()
return (
<>
{selectedItem && (
<h1>
Selected Item: {selectedItem.id} - {selectedItem.name}
</h1>
)}
<SelectionComponent />
</>
)
}
const App = () => {
const options = [
{ id: "1", name: "first" },
{ id: "2", name: "second" },
{ id: "3", name: "third" },
]
return (
<SelectionProvider options={options}>
<DisplayComponent />
</SelectionProvider>
)
})
}
Multiple Providers
It is also possible to use multiple nested providers with different contextId
properties.
...
const { options, selectItem } = useSelection("MyContextID")
...
<SelectionProvider options={options} contextId="MyContextID">
...