useSelection
The useSelection
hook provides a way of consuming and modifying which blocks are currently selected.
Usage
import {useSelection} from '@tinypixelco/wp-react-hooks'
const {selection, setSelection} = useSelection()
selection
import {useSelection} from '@tinypixelco/wp-react-hooks'const component = () => {const {selection} = useSelection()return (<div>{selection && JSON.stringify(selection)}</div>)}
The selection
object looks like this:
{attributes: {}clientId: "881d5ee3-1672-4607-8b65-1fa7877adf0d"innerBlocks: []isValid: truename: 'acme-co/acme-block'}
setSelection
This block will always be selected.
import {useSelection} from '@tinypixelco/wp-react-hooks'const component = ({clientId}) => {const {selection, setSelection} = useSelection()useEffect(() => {const notSelected = selection.clientId !== clientIdif (notSelected) {setSelection(clientId)}}, [selection])return (<div>Annoyingly, this block is always selected.</div>)}
Any actual use of setSelection
would likely involve you:
- Getting the block ID you want to select. There are other hooks in this library which may help.
- Developing criteria that needs to be met to trigger the selection (our example sidesteps this by just always firing, which is probably not what you want.)
- Calling
setSelection
when that criteria is met.
But, this example allows us to demonstrate the functionality of the component in isolation.