I'm building a Gutenberg block and am trying to show an input when an element is selected.
<RichText
tagName="a"
className="button"
placeholder={ __( 'Text...' ) }
keepPlaceholderOnFocus={ true }
value={ text }
onChange={ ( value ) => setAttributes( { text: value } ) }
/>
{ isSelected && (
<form
className="inline-input"
onSubmit={ ( event ) => event.preventDefault() }>
<URLInput
value={ URL }
onChange={ ( value ) => setAttributes( { URL: value } ) }
/>
</form>
) }
When the element with class name "button" is selected the form should show. Instead, the form shows from the start. Am I using isSelected wrong?
I am still learning REACT for Gutenberg/Block Editor. But I've managed to come up with a workaround for this.
You need to use an IF
conditional for the element (shorthand). You can use the className hidden
to show/hide an element.
<form
className={ !your_attribute ? "hidden" : "inline-input" }
onSubmit={ ( event ) => event.preventDefault() }>
<URLInput
value={ URL }
onChange={ ( value ) => setAttributes( { URL: value } ) }
/>
</form>
The isSelected
is used if the user has clicked on the block to make it "active". You can probably use states in this case as well. I just find this will keep the form showing if the user selected the button and then saves their post/page.
As mentioned, I'm still learning REACT + Gutenberg/Block Editor. I hope this helps.