I want to implement multiple check boxes (all selections/undoes all) in react.

Asked 2 years ago, Updated 2 years ago, 88 views

I am currently working on implementation with next.js, but as mentioned above, I would like to manage the check status of multiple check boxes with state, and if I press the button on a different component, the check status will be selected and released.
Also, multiple check boxes are made from api data and are rotated by map in child components.

Parent Components

export default function Favorite(){
    const testUrl='"
    const fetch=url=>fetch(url).then(r=>r.json())
    let data = useSWR(testUrl, fetchher)
    let newdata=data.data
    
    return(
        <FavoriteBuild changeChecked={changeChecked}checked={checked}data={newdata}/>  
        ↓ Press certain buttons on this component to clear all selections
        <UserFavoriteHeader/>

    )

Child Components

export default function FavoritecheckBox(props){
    let newdata=props.newdata
        return(
            {newdata.map(value,idx)=>(
                  <input onChange={props.changeChecked}checked={props.checked}>I want the parent component to manage the check state of input here
             ))}
        )
    }

The unnecessary code is omitted and written briefly.I'm sorry.
I looked into it, but I couldn't find much of this state management, so I would appreciate it if someone could tell me.

javascript reactjs next.js react-jsx

2022-09-30 19:55

1 Answers

You can achieve the expected behavior by managing the combination of "api data" and checkbox selection state in the parent component useState.

export default function Favorite(){
  const [state, setState] = useState();
  const testUrl=";
  const fetch=(url)=>
    fetch(url)
      .then(r)=>r.json())
      .then((json)=>{
        const newState=/* Generate a set of "api data" and checkbox selection states */[{apiData:{/*...*/}, checked: false}];
        setState(newState);
      });
  useSWR(testUrl, fetchher);
...

Sample Code


2022-09-30 19:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.