mardi 10 mai 2022

How to implement a checkbox using formik?

I want to implement a list of checkbox. The code right now is this:

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

/* MUI */
import { Box, Typography, CircularProgress } from '@material-ui/core';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';

/* Formik */
import { Field } from 'formik';

const TagInformation = props => {
    const tagSelector = useSelector((state) => state.products);
    const tagsData = tagSelector.list;

    return (
        <section>
            <Typography variant="h6"> Tag Information </Typography>
            {tagSelector.successful
                ? tagsData.content.map((tag) => (
                    <Box margin={1}>
                        <Field name="tags" label={tag.external_id} value={tag.id} component={FormControlLabel}
                        />
                    </Box>
                ))
                :
                <CircularProgress />
            }
        </section>
    )
};

TagInformation.label = 'Tag Information';
TagInformation.initialValues = {
    tags: []
};

export default TagInformation;

However, the value doesn't get saved.

I have an array of tags (example: [vegan, glutenFree, ...]) that I want to put in a list of Checkboxes.

As you can see in the initialValues we have the values that I want to put inside -> tags:[].

And the final result I want it like this: tags:[vegan, glutenFree, ...] or whatever checkbox is clicked. However when I click on submit I am seeing that the tags is empty -> tags:[]

I am using Formik in for the form and MUI for the design. And according to formik I can put a component in the field. I can visualize correctly in the website. But when I click on submit I don't see the value anywhere. I tried different things, but I don't know how to fix.

Any help?




Aucun commentaire:

Enregistrer un commentaire