javascript – WordPress Gutenberg: Attribute overwritten by block duplicate

Question

For a custom wordpress gutenberg block I’ve created a list of buttons so that users can add/remove as many as needed. While this works pretty fine one issue occurs: When duplicating a block the duplicate overwrites the array values of the origin block as long as we are in editing mode. After saving and refreshing the page the array values become independent. Is anyone aware of that behaviour?

// Simplified code:

// Attributes definition:
...
attributes: {
  buttons: {
    type: 'array',
    default: []
  }
}
...
const buttons = props.attributes.buttons
...
// Edit inspector controls:
buttons.length > 0 && buttons.map( function( button, index ) {
  return el(
    TextControl,
    {
      label: 'Text',
      value: button.text,
      onChange: function( newText ) {
        let newButtons = [ ...buttons ]
        newButtons[ index ][ 'text' ] = newText

        props.setAttributes( { buttons: newButtons } )
      }
    }
  )
}

// Edit / Save output:    
buttons.length > 0 && buttons.map( function( button, index ) {
  return el(
    'a',
    {
      key: 'button-' + index        
    },
    button.text
  )
} )

0
Kristo 2 months 2022-09-25T04:49:12-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse