Im trying to create a Gutenberg dynamic block with dropdown list. I have completed block creation and rendering the block with selected dropdown value in the frontend.
How to set the dropdown selected with previous value when editing a post?
I have tried to access attribute value using props.attributes
, but getting undefined
block.js
const { __ } = wp.i18n;
const { registerBlockType, RichText } = wp.blocks;
registerBlockType( 'gut/new-block', {
title: __( 'new-block - Test' ),
category: 'common',
attributes: {
category_id: {
type: 'number'
}
},
edit: function( props ) {
const { attributes: { category_id }, setAttributes } = props;
function setCategory( event ) {
const selected = event.target.querySelector( 'option:checked' );
setAttributes( { category_id: selected.value } );
event.preventDefault();
}
return (
<div className={ props.className }>
<select value={ category_id } onChange={ setCategory }>
<option value="120">Animals</option>
<option value="350">Architecture</option>
<option value="700">Nature</option>
<option value="800">People</option>
<option value="432">Tech</option>
</select>
</div>
);
},
save ( props ) {
return null
},
});
PHP
function gut_my_new_block() {
wp_register_script(
'gut-my-new-block',
plugins_url( 'new-block/dist/blocks.build.js', __FILE__ ),
array( 'wp-blocks', 'wp-element' )
);
register_block_type( 'gut/new-block', array(
'render_callback' => 'gut_render_block_my_newblock',
'editor_script' => 'gut-my-new-block',
) );
}
add_action( 'init', 'gut_my_new_block' );
function gut_render_block_my_newblock($params) {
return '<h3>selected category '.$params['category_id'].'</h3>';
}