skip to Main Content

I have multiple checkboxes which are created within map(loop). I am unable to add two functionalities:

  1. When user click on any checkbox, it shoud show that checkbox checked

  2. All event_id which are present in eventGoing variable should be checked by default.

    {
    products.map(post=>
    // eventGoing going contains list of event ids which i extracted from DB
    if(eventGoing.indexOf(event_id) > -1)
    {
    // need to check the checkbox if event_id is within eventGoing variable
    }

     <input  checked={checked} name="goingChk" value={"checkbox-"+post.event_id} type="checkbox" id={"checkbox-"+post.event_id} onClick={e => handleGoing(e, post.event_id)} />
     <br>    
    

    );
    }

Ignore the coding errors as i extracted the code from 2 different functional components.

Please help me out how can i get two functionalities mentioned above.

2

Answers


  1. Chosen as BEST ANSWER

    Complete code:

    const fetchDataEmpty = (setProducts) => {
        axios
        .get('/get_data.php')
        .then((res) => {
            setProducts(res.data);
        })
        .catch((err) => {
            console.log("Err:",err);
        });
    };
    
    const  ParentTile = (props) => {
        const [products, setProducts] = useState([]);
        
        
        useEffect(()=>{
              fetchData(setProducts)
            },[type]) // []
        
        
        return (
            <div> 
                {products.map(post=><div> 
                    <EventTile record={post}  />
                </div>);
            </div>);
        }
    
    }
    
    
    
    //EventTile.js
    
    const EventTile = (record) => {
        return <>
            Record.eventName
            <input  name="goingChk" value={"checkbox-"+record.event_id} type="checkbox" id={"checkbox-"+record.event_id} onClick={e => handleGoing(e, record.event_id)} />
            <br>
        <>
    }
    

  2. Problem:

    the problem is you are saving value on single boolean state, which is causing issue (checking all checkboxes)

    Solution

    Here is something you can try

     const products = []
      const [checkboxValues, setCheckboxValues] = React.useState(new Array(products.length).fill(false));
    
      const handleCheckboxChange = (index) => {
        const newValues = [...checkboxValues];
        newValues[index] = !newValues[index];
        setCheckboxValues(newValues);
      };
    
      return (
        <div>
          {checkboxValues.map((value, index) => (
            <input
              key={index}
              type="checkbox"
              checked={value}
              onChange={() => handleCheckboxChange(index)}
            />
          ))}
        </div>
      )
    

    You can use replace products array with your products array in this code and that should work just fine.

    Although if you want to do it inside your code you can do it like this

    Sure here’s updated example

    Complete code:

    const fetchDataEmpty = (setProducts) => {
        axios
            .get('/get_data.php')
            .then((res) => {
                const data = res.data?.map((item) => {
                    return { ...item, checkboxValue: false }
                })
                setProducts(res.data);
            })
            .catch((err) => {
                console.log("Err:", err);
            });
    };
    
    const ParentTile = (props) => {
        const [products, setProducts] = useState([]);
    
    
        useEffect(() => {
            fetchData(setProducts)
        }, [type]) // []
    
        const handleCheckboxChange = (index) => {
            const newValues = [...checkboxValues];
            newValues[index].checkboxValue = !newValues[index].checkboxValue;
            setCheckboxValues(newValues);
        };
    
        return (
            <div>
                {products?.map((item, index) => (
                    <input
                        key={index}
                        type="checkbox"
                        checked={item.checkboxValue}
                        onChange={() => handleCheckboxChange(index)}
                    />
                ))}
            </div>
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search