• Is there a way to pass a JS object from a parent block to its InnerBlocks?

    I’m building a block that requires initializing an expensive JS object.

    In pseudocode:

    js
    // Edit.js
    ...
    const myObj = new MyObj( ...blockAttributes );
    ...
    return (
     <> 
      <div>{myObj.someFunction()}</div> // outputting data from the JS object.
      <InnerBlocks /> // also needs to call myObj functions.
     </>
    );
    

    Ideally, I’d only initialize this object once in a parent block and pass it along to various child blocks that make use of different object methods.

    Ive tried storing the object as a block attribute, but the functions dont serialize, and I cant useContext() since child blocks dont share their parent block’s Context.Provider).

    Any ideas?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi there,
    Have you managed to find a solution to this?

    React’s Context component might work. Here are the docs for that.

    You could try wp.element.createContext to pass data down through a hierarchy of elements.

    Hope this helps
    -Jamie

    Thread Starter David Levine

    (@justlevine)

    Is there a way to add the created <Context.Provider> higher up in the DOM? Because otherwise, it won’t be passed to the InnerBlock, since it’s a slot, and not an actual child element (which was the issue with trying to use React.createContext natively)

    • This reply was modified 2 years, 7 months ago by David Levine.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sharing JS objects with inner blocks.’ is closed to new replies.