Handle Reset for specific field formik

Viewed 2283

I am new to react and I have just started using Formik I like how simple it makes making forms and handling forms in react. I have created multiple custom fields using formik, I am putting the react-select field I created as an example here.

import { ErrorMessage, Field } from "formik";
import React from "react";
import Select from 'react-select'

const SelectInput = (props) => {

  const { label, name, id,options, required, ...rest } = props;
  const defaultOptions = [
   {label : `Select ${label}`,value : ''} 
  ]
  const selectedOptions = options ? [...defaultOptions,...options] : defaultOptions
  return (
    <div className="mt-3">
      <label htmlFor={id ? id : name}>
        {label} {required && <span className="text-rose-500">*</span>}
      </label>
      <Field
        // className="w-full"
        name={name}
        id={id ? id : name} 
      >
          {(props) => {
          return (
            <Select
              options={selectedOptions}
              onChange={(val) => {
                props.form.setFieldValue(name, val ? val.value : null);
              }}
              onClick = {(e)=>{e.stopPropagation}}
              {...rest}
              // I want someting like onReset here
            ></Select>
          );
        }}
      </Field>
      <ErrorMessage
        name={name}
        component="div"
        className="text-xs mt-1 text-rose-500"
      />
    </div>
  );
};

export default SelectInput;

This is the usual code I use for submitting form as you can see I am using resetForm() method that is provided by formik, I want to attach the reseting logic in on submit method itself.

  const onSubmit = async (values, onSubmitProps) => {
    
    try {
      //send  request to api
      onSubmitProps.resetForm()
    } catch (error) {
      console.log(error.response.data);
    }
  };
3 Answers

If you want to reset the selected value after the form is submitted, you need to provide a controlled value for the Select component. The Formik Field component provides the value in the props object, so you can use it.

For example:

SelectInput.js

import { ErrorMessage, Field } from 'formik';
import React from 'react';
import Select from 'react-select';

const SelectInput = ({ label, name, id, options, required, ...rest }) => {
  const defaultOptions = [{ label: `Select ${label}`, value: '' }];
  const selectedOptions = options ? [...defaultOptions, ...options] : defaultOptions;

  return (
    <div className='mt-3'>
      <label htmlFor={id ? id : name}>
        {label} {required && <span className='text-rose-500'>*</span>}
      </label>
      <Field
        // className="w-full"
        name={name}
        id={id ? id : name}
      >
        {({
          field: { value },
          form: { setFieldValue },
        }) => {
          return (
            <Select
              {...rest}
              options={selectedOptions}
              onChange={(val) => setFieldValue(name, val ? val : null)}
              onClick={(e) => e.stopPropagation()}
              value={value}
            />
          );
        }}
      </Field>
      <ErrorMessage name={name} component='div' className='text-xs mt-1 text-rose-500' />
    </div>
  );
};

export default SelectInput;

and Form.js

import { Formik, Form } from 'formik';
import SelectInput from './SelectInput';

function App() {
  return (
    <Formik
      initialValues={{
        firstName: '',
      }}
      onSubmit={async (values, { resetForm }) => {
        console.log({ values });
        resetForm();
      }}
    >
      <Form>
        <SelectInput
          name='firstName'
          label='First Name'
          options={[{ label: 'Sam', value: 'Sam' }]}
        />
        <button type='submit'>Submit</button>
      </Form>
    </Formik>
  );
}

export default App;

Therefore, if you click the Submit button, value in the Select component will be reset.

You can also make a useRef hook to the Fromik component and then reset the form within the reset function without adding it as a parameter to the function.

https://www.w3schools.com/react/react_useref.asp It's one of the really nice hooks you'll learn as you progress through React :)

So if I understood you correctly you want to reset a specif field value onSubmit rather than resetting the whole form, that's exactly what you can achieve using actions.resetForm().

Note: If nextState is specified, Formik will set nextState.values as the new "initial state" and use the related values of nextState to update the form's initialValues as well as initialTouched, initialStatus, initialErrors. This is useful for altering the initial state (i.e. "base") of the form after changes have been made.

You can check this in more detail here.

And here is an example of resetting a specific field using resetForm() whereby you can see as you input name, email and upon submit only email field will get empty using resetForm.

import "./styles.css";
import React from "react";
import { Formik } from "formik";

const initialState = {
  name: "",
  email: ""
};
const App = () => (
  <div>
    <h1>My Form</h1>
    <Formik
      initialValues={initialState}
      onSubmit={(values, actions) => {
        console.log(values, "values");
        actions.resetForm({
          values: {
            email: initialState.email
          }
        });
      }}
    >
      {(props) => (
        <form onSubmit={props.handleSubmit}>
          <input
            type="text"
            onChange={props.handleChange}
            onBlur={props.handleBlur}
            value={props.values.name}
            name="name"
          />
          <br />
          <input
            type="text"
            onChange={props.handleChange}
            onBlur={props.handleBlur}
            value={props.values.email}
            name="email"
          />
          <br />
          <br />
          {props.errors.name && <div id="feedback">{props.errors.name}</div>}
          <button type="submit">Submit</button>
        </form>
      )}
    </Formik>
  </div>
);
export default App;

Related