Bob KapusAkba
Bob KapusAkba

Reputation: 65

React hooks, does not change the checked property to checkbox

I am trying to change the ckeckbox property, every time I write a new value to the map, in my case when I click on the checkbox, it only changes the value of the checked property, for example, the initial value is true, on all subsequent clicks it will be false, false, false ... What's wrong here?

import React,{ useState,useEffect } from "react";
import {useSelector} from 'react-redux'

const ChangeArticle = (props) => {

    const prevArticle = props.changeArtcle;
    const age_groups = useSelector(state => state.app.age_groups);
    const [checkedAges, setCheckAges] = useState(new Map());

    const handleChangeCheckBoxe = (event) => {
        
        setCheckAges(checkedAges => checkedAges.set(event.target.value, event.target.checked));
        console.log("checkedItems: ", checkedAges);

    }

    useEffect(() => {

        if(prevArticle.ages){
            prevArticle.ages.forEach((age) =>{
                setCheckAges(checkedAges => checkedAges.set(age.toString(), true));
            });
        }
            

    },[prevArticle]);

    return (<div>
        
            {age_groups.map(age => {
                
                return (<div key={age.id}>
                     <input type="checkbox" checked={checkedAges.has(age.id.toString()) ? checkedAges.get(age.id.toString()) : false} value={age.id} onChange={handleChangeCheckBoxe}
                />
                { age.title }
                </div>) 
                
            }) }
    </div>);
}

export default ChangeArticle;

Upvotes: 0

Views: 419

Answers (1)

nipuna-g
nipuna-g

Reputation: 6652

In the handleChangeCheckBoxe function, you are only changing the values withing the Map. React only does a shallow reference check to see if the Map had changed. Since the reference is the same, the it will not re-render the component as you would expect.

You can change the function to be similar to the following to create a new Map and assign it to state.

  const handleChangeCheckBoxe = (event) => {
      setCheckAges(checkedAges => new Map(checkedAges.set(event.target.value, event.target.checked)));
      console.log("checkedItems: ", checkedAges);
  }

You can see this working in the following code sandbox https://codesandbox.io/s/wispy-leftpad-9sji0?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 1

Related Questions