mardi 7 avril 2020

React checkbox refreshes page after each click, and on the front it doesn't show me that it has been checked

My problem is that after I check the input checkbox, it doesn't show me "tick" that it is cheked, but in debugger mode it shows "true" for checked. In my code, I have get request to show me all the ingredients, and the user can choose them.

After clicking/checking, there is a function onIngredientsChange, and there I want to send a list ings[] to my parrent component with id-s of all checked ingredients. Can someone help me?

Here is my component:

const Ingredient = (props) => {


    const onIngredientChange = (e) => {

        setChecked(e.target.checked);
        document.getElementById(e.target.value + "amount").disabled = !document.getElementById(e.target.value + "amount").disabled;

        if(e.target.checked){
            ings.push(e.target.value)
        }
        props.onIngredientChange(ings);
    };



    let [ingredients, setIngredient] = useState();
    const [checked, setChecked] = React.useState(false);
    let ings= [];

    useEffect(() => {
        axios.get("/ingredients").then((data) => {
            const ingredients = Object.keys(data.data).map((ingredient, index) => {
                return (
                    <tr key={index}>
                        <td scope="col">
                            <label>{data.data[index].name}</label>
                        </td>
                        <td scope="col">
                            <input id={ingredient} onChange={onIngredientChange} key={index} type="checkbox"
                                   name={"newIngredients"} value={data.data[index].id}  checked={checked}
                            />
                        </td>
                        <td scope="col">
                            <input  id={data.data[index].id + "amount"} key={index} type="number"
                                    min="0" max="500" disabled
                                    name="amount" placeholder="grams" onChange={onIngredientChange}/>

                        </td>
                    </tr>
                );
            });
            setIngredient(ingredients);
        });
    }, []);

    return(

        <div className="form-group">
            <table className="table tr-history table-striped small">
                <thead>
                <tr>
                    <th scope="col">
                        <h5>Ingredient</h5>
                    </th>
                    <th scope="col">
                        <h5>Check</h5>
                    </th>
                    <th scope="col">
                        <h5>Amount</h5>
                    </th>
                </tr>
                </thead>
                <tbody>
                {ingredients}
                </tbody>
            </table>
        </div>

    )  
}
export default Ingredient;



Aucun commentaire:

Enregistrer un commentaire