In gutenberg editor I need to get a ref to the BlockListBlock element but it doesn’t seem to work. Is there a way to achieve this ?
const withCustomAttribute = createHigherOrderComponent(
(BlockListBlock) => {
return (props) => {
const blockRef = createRef();
useEffect(() => {
console.log(blockRef); // => "{current: null}"
});
return <BlockListBlock {...props} ref={blockRef} />;
};
},
'withCustomAttribute'
);
addFilter(
'editor.BlockListBlock',
'example/custom-attribute',
withCustomAttribute
);
2
Answers
I don’t think that there is an easy way to achieve what you want, because
<BlockListBlock />
does not support any kind ofref
passing.You can see the source code here.
useRef
instead,createRef
won’t save the value between re-renders.useEffect
. Since it’s not a react state, react won’t trigger when it’s changed. Instead, you can add wrap your console.log inside a setTimeout.Something like this should give you the result you’d like: