skip to Main Content

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


  1. 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.

    Login or Signup to reply.
    1. You should use useRef instead, createRef won’t save the value between re-renders.
    2. 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} />;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search