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
);
CodePudding user response:
I don't think that there is an easy way to achieve what you want, because <BlockListBlock />
does not support any kind of ref
passing.
You can see the source code here.
CodePudding user response:
- You should use
useRef
instead,createRef
won't save the value between re-renders. - You can't track it on the
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} />;