How do I have two RadioControls in my custom Gutenberg block?
Sorry if this is a silly question but I am very new to WordPress and I am very new to Gutenberg Blocks…
So, I created a new block using npx wordpress user/create-block
, In my custom block I wish to add some radio buttons to determine css modifiers that I will store in my attributes object. Here is edit.js code, which I have simplified for readability.
export default function Edit(props) {
const [ option, setOption ] = useState( props.attributes.blockType || '' );
const optionDir = useState( props.attributes.blockType || '' ).option;
return (
<div { ...useBlockProps() }>
<div>
<RadioControl
label="Set the style of the block"
selected={ option }
options={ [
{ label: 'default - #40ADAD', value: '' },
{ label: 'kleidershrank - #0D6575', value: 'uber-mich--kleidershrank' },
{ label: 'homeoffice - #D5B46E', value: 'uber-mich--homeoffice' },
{ label: 'umzug - #FF7161', value: 'uber-mich--umzug' },
{ label: 'pricing - #143F6B', value: 'uber-mich--pricing' }
] }
onChange={ ( value ) => {
setOption( value );
props.setAttributes({blockType: value })
} }
/>
<RadioControl
label="Reverse order of the block "
selected={ optionDir }
options={ [
{ label: 'image first', value: '' },
{ label: 'text first', value: ' uber-mich__list--reverse' },
] }
onChange={ ( value ) => {
setOption( value );
props.setAttributes({direction: value })
} }
/>
</div>
<div className={`uber-mich ${props.attributes.blockType || ''}`}>
<div className={`uber-mich__list ${props.attributes.direction || ''}`}>
</div>
</div>
<!-- the rest of the block -->
);
}
I know I am doing something very wrong here, I am confused with the option
and setOption
properties that are being returned from the useState
function. I introduced a second option variable to prevent the reuse of the option variable overwriting the wrong attribute property, for example – this is pretty ugly!
const optionDir = useState( props.attributes.blockType || '' ).option;
What is strange is that this does produce the visual affect I require and the appropriate attribute values are stored… but the radio buttons in the RadioControls do lose their selected status… I need to set up both controls so they are independent of each other. Can someone help me achieve and understand this. If it helps here is my attributes object:
"attributes": {
"blockType": {
"type": "string"
},
"direction": {
"type": "string",
"default": ""
},
"title": {
"type": "string"
},
"strapline": {
"type": "string"
},
"copy": {
"type": "string"
}
}
Leave an answer