• islandscott

    (@islandscott)


    Hi,

    Im trying to create a custom block which includes owl carousel but it seems like owl carousel is initialising before the inner blocks are rendered so its not wrapping the correct divs.

    Any idea how I can run a piece of js after the inner blocks have been rendered ?

    thanks.

Viewing 1 replies (of 1 total)
  • To achieve this, you can use the useEffect hook from the wp.element package to run your JavaScript code after the inner blocks have been rendered.

    Here’s an example of how you can do this in your custom block:

    // Import necessary dependencies
    const { registerBlockType } = wp.blocks;
    const { InnerBlocks, useBlockProps } = wp.blockEditor;
    const { useEffect } = wp.element;
    
    // Create your custom block
    registerBlockType('yournamespace/your-block', {
      title: 'Your Custom Block',
      category: 'design',
      edit: (props) => {
        const blockProps = useBlockProps();
    
        // Initialize Owl Carousel after inner blocks have been rendered
        useEffect(() => {
          const owlContainer = document.querySelector('.owl-carousel');
    
          if (owlContainer) {
            jQuery(owlContainer).owlCarousel({
              // Owl Carousel options go here
            });
          }
        }, []);
    
        return (
          <div {...blockProps}>
            <div className="owl-carousel">
              <InnerBlocks />
            </div>
          </div>
        );
      },
      save: (props) => {
        const blockProps = useBlockProps.save();
        return (
          <div {...blockProps}>
            <div className="owl-carousel">
              <InnerBlocks.Content />
            </div>
          </div>
        );
      },
    });
    

    In this example, I used the useEffect hook with an empty dependency array []. This means the effect will run only once after the component mounts. Inside the effect, I initialize the Owl Carousel using the container with the class .owl-carousel.

    Make sure to replace yournamespace/your-block with your own block namespace and name, and customize the Owl Carousel options as needed.

Viewing 1 replies (of 1 total)
  • The topic ‘Executing JS after inner blocks have been rendered’ is closed to new replies.