0

I have this component, it is supposed to work as some sort of extra-entering-dialog. It is imported in Edit function of the block.

/**
 * Component for entering biography
 */

import { InnerBlocks } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';
import { useState } from '@wordpress/element';



const BiographyModal = ({ name }) => {
    const [ isOpen, setIsOpen ] = useState(false);
    const modal =
        <div className="biography-modal">
            <h3>{ `Životopis ${ name }` }</h3>
            <InnerBlocks />
            <Button isDefault onClick={ () => setIsOpen({ isOpen: false }) }>
                Završi uređivanje
            </Button>
        </div>;

    return (
        <div>
            <Button isDefault onClick={ () => setIsOpen({ isOpen: true }) }>Uredi životopis</Button>
            { isOpen && modal }
        </div>
    )
}

export default BiographyModal;

It does open on button lower in code, but it does not close when clicking on button higher in code. It won't even close when I change state of isOpen by using React developer tools in browser. At first I thought this was because dismounting of InnerBlocks or Button is not allowed, but after I remove those two (and give lower button possibility to function as toggle button (setIsOpen({ isOpen: ! isOpen })), this still does not close. Any clues?

0

The problem is that you're using setIsOpen() incorrectly.

Your code initialises isOpen as false, and your code implies that it can be either true or false, but that's not what you're setting it as. The setIsOpen() function updates isOpen to the value you pass to it, and you're passing an object with an isOpen property, not a boolean value.

When you call setIsOpen({ isOpen: false }), you're not setting isOpen to false, you're setting it to { isOpen: false }. You need to just pass true or false:

<Button isDefault onClick={ () => setIsOpen(false) }>

Note that this is React functionality, not anything to do with WordPress, so you should review the documentation for useState().

1
  • Yes, I was to much used to setAttribute syntax to notice the error.
    – Lovor
    Oct 2 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.