Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass values to the state from formik

Tags:

reactjs

formik

I use formik for forms in my react app.

class myComponent extends Component {
  constructor(props) {
    this.state = {
      inputData: {}
    }
  }

render() {
  return(
    <Formik>{({ errors, handleChange, values }) => (
      console.log(values);
      <Field type="text" name="address" onChange={handleChange} />
   )}
   </Formik>
  )
}
}

The question: how i can pass values to the state?

like image 294
Lamer_2005 Avatar asked Dec 07 '25 05:12

Lamer_2005


1 Answers

I think the recommended best practice is to only use Formik state in order to avoid any side effects of having the state stored in 2 locations (Formik + the component state). I was also looking to achieve what you wanted and found the following component - https://github.com/jaredpalmer/formik-effect - that will let you decorate the handleChange function. However after reading the README for this component I decided to only use the Formik state and pass it's values to any function that require values within that state.

To pass the values to a function I used the following pattern:

class Example extends Component {
    handleValues(values) {
        // Do something with values
    }

    render() {
        return (
            <Formik>
                ({values}) => {<button onClick={() => this.handleValues(values)}>Do something</button>}
            </Formik>
        );
    }
}
like image 186
Castrohenge Avatar answered Dec 08 '25 20:12

Castrohenge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!