Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom change handlers with inputs inside Formik

Tags:

reactjs

formik

I'm porting some of my forms I made using SUIR over to a Formik implementation. I have input components that need custom change handlers to perform actions. How can I pass my change handler to the onChange prop so the values are tracked by formik?

I've tried something like this, but with no luck.

onChange={e => setFieldValue(dataSchemaName, e)}

which is mentioned in a different post here.

It's also mentioned here, but I can't quite get my custom change handler to hook up nicely with Formik.

My change handler looks like this

handleSchemaChange = (e, { value }) => {
  this.setState({ dataSchemaName: value }, () => {
     console.log("Chosen dataSchema ---> ", this.state.dataSchemaName);
     //also send a request the selfUri of the selected dataSchema
  });
  const schema = this.state.dataschemas.find(schema => schema.name === value);
if (schema) {
  axios
    .get(schema.selfUri)
    .then(response => {
      console.log(response);
      this.setState({
        fields: response.data.data.fields,
      });
      console.log(this.state.fields);
    })
    .catch(error => console.log(error.response));
  }
};

Here's an example of one of my form fields using a dropdown

<Form.Field>
  <label style={{ display: "block" }}>
    Select a Schema
  </label>
  <Dropdown
    id="dataSchemaName"
    multiple={false}
    options={dataschemas.map(schema => {
      return {
        key: schema.id,
        text: schema.name,
        value: schema.name
      };
    })}
    value={dataSchemaName}
    onChange={this.handleSchemaChange}
  />
</Form.Field>

I have a sandbox with the issue

like image 639
DJ2 Avatar asked Jan 26 '23 04:01

DJ2


1 Answers

You can pass the setFieldValue function to your function handleSchemaChange and then use it inside.

So, instead of onChange={this.handleSchemaChange} make it onChange={(e, val) => this.handleSchemaChange(e, val, setFieldValue)}.

And inside your handleSchemaChange function:

handleSchemaChange = (e, { value }, setFieldValue) => {
    setFieldValue('dataSchemaName', value);
    ... the rest of your implementation
}

Here is a sandbox with the solution implemented: https://codesandbox.io/s/formik-create-query-schema-uq35f

like image 159
3b3ziz Avatar answered Feb 19 '23 03:02

3b3ziz