wordpresswordpress-gutenberggutenberg-blocks

Gutenberg dynamic SelectControl values object


I want to dynamically pass the options object to Gutenberg SelectControl:

el( SelectControl, {
    label: __( 'Animation' ),
    value: props.attributes.animation,
    onChange: ( value ) => { props.setAttributes( { animation: value } ); },
    options: [
      { value: 'date', label: __( 'One column' ) },
      { value: 'title', label: __( 'Two columns' ) },
    ],
  }
),

I have a PHP function that returns an object of available animations?

function animation( ) {
    $animations = array(
                        ''                  => 'none',
                        'fade'              => 'fade',
                        'fade-up'           => 'fade-up',
                        'fade-down'         => 'fade-down',
                        'zoom-out-up'       => 'zoom-out-up',
                        'zoom-out-down'     => 'zoom-out-down',
                        'zoom-out-left'     => 'zoom-out-left',
                        'zoom-out-right'    => 'zoom-out-right'
                );

    return apply_filters( '_animations', $animations );
}

Solution

  • I have used wp_localize_script to get the array as object in JS:

    $variables['animations'] = _functions::_animation();
    wp_localize_script( $this->plugin_name, 'meetongo', $variables );
    

    and you can access that object like this:

    console.log( meetongo.animations );