2.1.0 • Published 3 years ago

@truefit/bach-formik v2.1.0

Weekly downloads
11
License
MIT
Repository
github
Last release
3 years ago

@truefit/bach-formik

This library allows components composed with @truefit/bach to idiomatically use Formik

Installation

npm install @truefit/bach-formik formik

or

yarn add @truefit/bach-formik formik

Enhancers

withFormik

Allows you to specify that the composed component should be wrapped in a Formik element. This enhancer uses the Formik component.

Helper Signature

ParameterTypeDescription
formikPropsjs objecta js object containing the props to pass to the formik element - see formik documentation for full list

Example

Typescript

import React from 'react';
import {compose, withCallback} from '@truefit/bach';
import {withFormik} from '@truefit/bach-formik';
import {FormikProps} from 'formik';

type FormValues = {
  name: string;
  address: string;
  age: number;
};

type Props = {
  handleFormSubmit: () => void;
  formik: FormikProps<FormValues>;
};

const WithFormik = ({formik: {values, handleChange, handleBlur}, handleFormSubmit}: Props) => (
  <div>
    <input name="name" onChange={handleChange} onBlur={handleBlur} value={values.name} />
    <input name="address" onChange={handleChange} onBlur={handleBlur} value={values.address} />
    <input name="age" onChange={handleChange} onBlur={handleBlur} value={values.age} />

    <button type="submit" onClick={handleFormSubmit}>
      Submit
    </button>
  </div>
);

export default compose(
  withFormik({
    initialValues: {name: 'John Doe', address: '', age: 0},
    onSubmit: (values: FormValues) => {
      console.log(values); // eslint-disable-line
    },
  }),

  // this is needed to handle the type disparity between formik and onClick
  withCallback<Props>('handleFormSubmit', ({formik: {handleSubmit}}: Props) => () => {
    handleSubmit();
  }),
)(WithFormik);

Javascript

import React from 'react';
import {compose} from '@truefit/bach';
import {withFormik} from '@truefit/bach-formik';

const WithFormik = (formik: {values, handleChange, handleBlur, handleSubmit}) => (
  <div>
    <input
      name="name"
      onChange={handleChange}
      onBlur={handleBlur}
      value={values.name}
    />
    <input
      name="address"
      onChange={handleChange}
      onBlur={handleBlur}
      value={values.address}
    />
    <input
      name="age"
      onChange={handleChange}
      onBlur={handleBlur}
      value={values.age}
    />

    <button type="submit" onClick={handleSubmit}>
      Submit
    </button>
  </div>
);

export default compose(
  withFormik({
    initialValues: {name: 'John Doe', address: '', age: ''},
    onSubmit: values => {
      console.log(values); // eslint-disable-line
    },
  }),
)(WithFormik);
2.1.0

3 years ago

2.0.5

3 years ago

2.0.4

3 years ago

2.0.3

4 years ago

2.0.2

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.1.1

4 years ago

1.1.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago