Home > Software design >  Form handling using Formik library in react js
Form handling using Formik library in react js

Time:12-30

I want to handle three form in single component with suitable initialValues and Schemas, since I'm using formik and yup for form handling and validation. (is it okay to do such practice?)

const initialValuesLogin = { name: '', email: '', password: '' };

const initialValuesBookTable = {
  name: '',
  date: '',
  time: '',
  contact: '',
  details: '',
};

const initialValuesRegister = {
  name: '',
  email: '',
  password: '',
  confirm_password: '',
};

const [register, setRegister] = useState(true);
`this State is used to handle the toggle between login-form and register-form`;
const [username, setUsername] = useState('');

const { values, errors, handleBlur, handleChange, handleSubmit, touched } =
  useFormik({
    initialValues:
      props.show === 'loginForm'
        ? register
          ? initialValuesRegister
          : initialValuesLogin
        : initialValuesBookTable,
    validationSchema:
      props.show === 'loginForm'
        ? register
          ? registerSchema
          : loginSchema
        : bookTableSchema,
    onSubmit: (values, action) => {
      action.resetForm();
      setUsername(values.name);
    },
  });

I tried to handle three different forms in single component so basically there are 3 forms as- login, register and booktable. I've created different initialValues for all of them as well as schemas, and I've used multiple ternary operators but the issue is when I submit form for login it takes initialvalues of registered form but I just want that it should take values as per selected forms like(for 'login' it takes 'initialValuesLogin' and similarly for 'register' it takes 'initialValuesRegister') Btw it works fine for booktable form !!

CodePudding user response:

I'm using multiple form submissions in same components like below.

 const loginValidation = Yup.object({ });

const loginFormik = useFormik({
  initialValues: loginInitialValue ,
    validateOnChange: false,
    validateOnBlur: true,
    validationSchema: loginValidation ,
    onSubmit: (values) => {}

});

 const registerValidation = Yup.object({ });

const registerFormik = useFormik({
  initialValues: registerInitialValue ,
    validateOnChange: false,
    validateOnBlur: true,
    validationSchema: registerValidation ,
    onSubmit: (values) => {}

});

 const booktableValidation = Yup.object({ });

const booktableFormik = useFormik({
  initialValues: booktableInitialValue ,
    validateOnChange: false,
    validateOnBlur: true,
    validationSchema: booktableValidation ,
    onSubmit: (values) => {}

});
  • Related