• When registering a custom block type. How can one trigger a re-render or update of the block in the editor page.

    Example.

    Let’s say I have registered a block whose edit() function return’s a value of

    
    <>
    <BlockControls><IconButton icon="edit" onclick="toggleBoolean/></BlockControls>
    {myBoolean ? <Some_JSX_a>...</Some_JSX_a> : <Some_JSX_b>...</Some_JSX_b>};
    </>
    

    Now, this doesn’t work, and I am struggling with some key concepts.

    First, where do I store myBoolean… if this were a regular react app I might keep this in the state of a stateful component.

    2nd. How do I tell the editor to re-render the block when my button’s click callback fires so that it has the chance to re-evaluate my ternary operator and make the choice between which JSX snippet to render?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter willdelphia

    (@willdelphia)

    It turns out that the new ACF beta does something very similar to what I am trying to achieve. I took a look at their code and it turns out they store their version of the myBoolean value in the block’s attributes.

    I had had this thought while thinking on the problem but didn’t want to go down that road because it would basically result in extraneous text being added to the html comment markup for the block — it really doesn’t have anything to do with how the block is rendered on the front end of the site so it seems wrong to muck up attribute JSON.

    Is there another way to achieve this? Or did the ACF team get it right / find the only solution?

    As far as I am aware you store your event handlers as methods of your edit method, but I have only recently started toying with the blocks API myself, so I am not sure what your options are.

    An example – with ugly code, but also with a toggle! – is given in https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/

    • This reply was modified 5 years, 11 months ago by hatesspam.
    Thread Starter willdelphia

    (@willdelphia)

    So you’re right about the method storage. But it’s actually the state that I am trying to figure out.

    In react when you modify the state it triggers a re-render which updates the output HTML (as needed). I am trying to figure out if there is something like this in the WP Gutenberg API other than the attributes.

    I am sorry, I am just not familiar enough with the JSX syntax, I currently render everything with wp.element.createElement() calls due to a severe case of bloated tool stack allergy.

    (Just kidding. About the allergy, that is.)

    But if you call an event handler in the onClick attribute, should you then not define that event handler somewhere? Do you get error messages?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to trigger rerender of (gutenberg) block based on boolean variable value?’ is closed to new replies.