Reputation: 441
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
);
Upvotes: 3
Views: 1344
Reputation: 824
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:
const blockRef = useRef();
useEffect(() => {
setTimeout(()=>{
console.log(blockRef); // => "{current: null}"
}, 100)
});
return <BlockListBlock {...props} ref={blockRef} />;
Upvotes: 1