mercredi 17 février 2021

How to toggle a list element according to its checkbox?

I have a list of items in my React project with checkboxes and I'm unable to toggle the list item's background color according to whether the checkbox is checked. I keep track of a variable (apNumber) when a checkbox has been checked and tried using that to set a value selected=true in my data. It works when I check a box but when unselecting it the item's 'select' value doesn't get set back to false. Here's my code:

const [plots, setPlots] = useState([]);
const [checkedPlots, setCheckedPlots] = useState({})

useEffect(() => {
        getContent('farmPlot', {}).then((data) => {
            if (Array.isArray(data)) {
                data.map((p) => {
                    p.selected = false
                    return p
                })
            }
            setPlots(data);
        });

        let trueValues = Object.keys(checkedPlots).filter(p => checkedPlots[p] === true)

        setPlots(plots.map(plot => trueValues.includes('' + plot.apNumber) ? { ...plot, selected: 
        true } : { ...plot, selected: false }))

    }, [checkedPlots]);

const handleCheckboxSelection = (e) => {
        setCheckedPlots({ ...checkedPlots, [e.target.name]: e.target.checked })
} 

inside return:

                    <ListGroup>
                        {(plots) ? plots.map(p =>
                            <div style={plotRowStyle} key={p.apNumber}>
                                <Form.Check
                                    type='checkbox'
                                    style={checkboxStyle}
                                    value={checkedPlots}
                                    name={p.apNumber}
                                    checked={!!checkedPlots[p.apNumber]}
                                    onChange={(e) => handleCheckboxSelection(e)}
                                />
                                <ListGroup.Item
                                    style=
                                    key={p.apNumber}
                                    action onClick={() => farmPlotClickHandler(p)}>{p.name} - {p.apChar}, {p.area} ha ({p.plantName})
                                </ListGroup.Item> 
                            </div>
                        ) : ''}
                    </ListGroup> 



Aucun commentaire:

Enregistrer un commentaire