0

Is it possible to bind checked on a group of radio buttons generated in a loop and have the checked state be determined by the state?

Strangely enough in my current setup the last value is checked although 2 is in the state. If I click on a value it is correctly set in the state and input field but not the right checkbox shows checked. You need to click twice to have it look checked... Except when choosing 2 which is similar to the state value.

I am puzzled.

The behavior changes depending on using strings or integers??? '1' versus 1

Is this a timing or rerender issue? Is bind even supported? IMHO it should be.

How to get this working?

view.js:

import { store, getContext } from '@wordpress/interactivity';

const { state } = store( 'example', {
    state: {
        answers: [ 1, 2, 3, 4 ],
        chosen: 2,
    },
    actions: {
        handle: () => {
            const context = getContext();
            console.log( context.answer );
            state.chosen = context.answer;
            console.log( state );
        },
    },
} );

render.php

<div <?php echo get_block_wrapper_attributes(); ?> data-wp-interactive="example"
    <?php echo wp_interactivity_data_wp_context( array() ); ?>>
    <div>
        <template data-wp-each--answer="state.answers">
            <input type="radio" data-wp-bind--checked="state.chosen" name="choice" data-wp-bind--value="context.answer"
                data-wp-on--click="actions.handle">
            <label for="" data-wp-text="context.answer">
            </label>

        </template>
    </div>
    <input data-wp-bind--value="state.chosen" type="text">
</div>

1 Answer 1

3

Credits to https://github.com/sirreal on https://github.com/WordPress/gutenberg/discussions/63595

His answer works:

This directive is binding the value in state to the attribute checked: data-wp-bind--checked="state.chosen"

The result is that all of the inputs have the attribute checked="2".

You'll want to use derived state to bind the checked value to a boolean like this:

const { state } = store( "example", {
  state: {
    get isChecked() {
      return getContext().answer === state.chosen;
    },
  },
} );

And bind the checked value accordingly: data-wp-bind--checked="state.isChecked"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.