2

I'm at a loss here. Here is the relevant code I have:

const TraitModal = (props) => {
const [abiltiesChecked, setAbiltiesChecked] = React.useState(new Map());
const handleAbilitiesCheck = (e) => {
        var newabilitiesCH=abiltiesChecked.set(e.target.id, e.target.checked);
        setAbiltiesChecked(newabilitiesCH);
    };
return(
<Form>
GetAbilities().map((a) => (
                                        <div key={`custom-${a}-2`}>
                                            <Form.Check
                                                custom
                                                checked={!!abiltiesChecked.get(`abilities-${a}`)}
                                                type="checkbox"
                                                id={`abilities-${a}`}
                                                label={`${a}`}
                                                onChange={handleAbilitiesCheck.bind(this)}
                                            />
                                        </div>
                                    ))}
</Form>
    );
    }


In my understanding the setAbiltiesChecked(newabilitiesCH) replaces the old abiltiesChecked and thus would cause the React component to rerender, however that's not whats happening at all. The state does get updated as I figured out with some console logs, but it does not get updated from handleAbilitiesCheck function.

I have another function that basically rerenders on a input into a text box and that triggers a rerendering of the checkboxes, but I need them to show that the checkbox was actually clicked, whats the error with my code?

1 Answer 1

4

Your problem is that you're mutating your stateful object (your call to state changes the current map object), then assigning to it. React performs a diff on the object, sees no change, and therefore does not re-render.

In this specific case, replace:

    var newabilitiesCH=abiltiesChecked.set(e.target.id, e.target.checked);

with

    var newabilitiesCH= new Map(abiltiesChecked).set(e.target.id, e.target.checked);

The new copy should be recognized by React as a new state.

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.