Search code examples
wordpressreactjsblockjsxwordpress-gutenberg

Is there a function to that creates a custom block inside my gutenberg block?


I'm making a slider block and I want to create a slide block for each image I choose.

I already have a fully functioning slide block. The question is, how can I create call the slide block from the slider block? I think there must be a way through the API and I found the function createBlock() but nothing is really working

const { createBlock } = wp.blocks;
//
// some code
//
<div id={ listId } className={ classes } key={ index }>
  {createBlock('illmatic6514/slide')}
</div>

I'm expecting a slide block to be created. (To make it simple I removed variables from the slide block and put in a static image) I'm getting "Cannot read property 'attributes' of undefined"

Even if I call createBlock('core/paragraph') I get "Objects are not valid as a React child"


Solution

  • You probably want to define Slide as a component instead of a block:

    function Slide(props) {
      return <div>{props.slideName}</div>;
    }
    

    Or as a class that extends Component:

    const { Component } = wp.element
    class Slide extends Component {
      render() {
        return (
          <div>{ this.props.slideName }</div>
        )
      }
    }
    

    And then in your Slider block you would use that component:

    edit(props) {
      return (
        <div>
          <Slide slideName="Slide 1" />
          <Slide slideName="Slide 2" />
        </div>
      )
    }
    

    https://reactjs.org/docs/components-and-props.html