Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
How to set the value of form field based on another form field using react, typescript and formik?

i want to set the value of toggle switch based on another form field that user has set using react, typescript and formik.

what i am trying to do? code is like below

in constants file

export const OPTION_KEY = 'option';
export const SWITCH_KEY = 'switch';
export const initialValues: SomeValues = {
    [OPTION_KEY] = '',
    [SWITCH_KEY] = '',
}; 

in another file

import {OPTION_KEY, SWITCH_KEY} from 'constants';

const options: SelectOption[] = [
    { value: 'option1', label: 'option1' },
    { value: 'option2', label: 'option2' },
    { value: 'option3', label: 'option3' },
];

const FirstStep = ({formikBag} : formikBag: FormikProps<SomeValues>;}) => {
    return(
        <FormField label="Option" fieldId={OPTION_KEY}>
            {({field, form}: FieldProps) => (
                <Select
                    id={field.name}
                    inputId={field.name}
                    onChange={(option: SelectOption) =>
                        form.setFieldValue(field.name, option.value)
                    }
                    options={options}
                    placeholder={options[0].label}
                    value={options.filter(option=> option.value === field.value)}
                />
            </FormField>
            <FormField label="switch" fieldId={SWITCH_KEY}>
                {({ field, form }: FieldProps) => (
                    <Switch
                        id={'switch'}
                        {...field}
                        checked={isSwitchToggled}
                        onChange={() => {
                                form.setFieldValue(SWITCH_KEY,'');
                        }
                    }}
                />
            )}
        </FormField>
    )};

Now what i want to do is, when user selects option1 or option2 in select menu (that is OPTION_KEY) then by default i want the SWITCH_KEY to be turned off. if user selects option3 then by default SWITCH_KEY should be turned on.

now user can also toggle the SWITCH_KEY on or off even though option selected by user is option1 or option2 or option3.

how can i modify the above code meaning how should i set the SWITCH_KEY state based on option user selected and then if user toggles it how can i set SWITCH_KEY to on or off. could someone help me with this.

I am new to using formik and react. thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Keep the state of your switch somewhere in the component's state, eg. isSwitchToggled (idk what this variable isSwitchToggled of yours is doing, but it sure looks like a state variable) and just modify that state var based on the option chosen. Then, render your switch accordingly:

const FirstStep = ({formikBag} : formikBag: FormikProps<SomeValues>;}) => {
    const [isSwitchToggled, setSwitchToggled] = React.useState(false);

    const setSwitch = (fieldName, fieldValue) => {
        if (fieldName === 'name' && fieldValue === 'John') {
            setSwitchToggled(true);
        } else setSwitchToggled(false);
    }

    return(
        <FormField label="Option" fieldId={OPTION_KEY}>
            {({field, form}: FieldProps) => (
                <Select
                    id={field.name}
                    inputId={field.name}
                    onChange={(option: SelectOption) =>
                        form.setFieldValue(field.name, option.value)

                        setSwitch(field.name, option.value)
                    }
                    options={options}
                    placeholder={options[0].label}
                    value={options.filter(option=> option.value === field.value)}
                />
            </FormField>
            <FormField label="switch" fieldId={SWITCH_KEY}>
                {({ field, form }: FieldProps) => (
                    <Switch
                        id={'switch'}
                        {...field}
                        checked={isSwitchToggled}
                        onChange={() => {
                                form.setFieldValue(SWITCH_KEY,'');
                        }
                    }}
                />
            )}
        </FormField>
    )};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda