jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.97k stars 2.79k forks source link

New Examples / Sandboxes #1315

Open jaredpalmer opened 5 years ago

jaredpalmer commented 5 years ago

Going through a lot of issues yesterday, I think it would be great to add some new sandboxes/examples:

Nice to have

EfstathiadisDimitris commented 5 years ago

I can handle checboxes if that's ok. But a couple of questions. Could we get a little more explanations regarding the other 3. What is the requirements.

If you can provide more scenarios I would be happy to help...

billdybas commented 5 years ago

I made a sandbox for #1205. Let me know if there's anything to improve / if we should move it into an example. I believe that issue was talking about two selects which are always shown where choosing an option in the first select changes what options are available in the second select.

If desired, I can make another sandbox where a select's selected value will hide/show another field.

jamesmosier commented 5 years ago

I created two examples for masked inputs.

  1. Based off of the input primitives example to allow for regular or masked inputs using the same component: https://codesandbox.io/s/7259y11530
  2. A very basic example of how to use react-text-mask: https://codesandbox.io/s/248vzprz2p
denis-souzaa commented 5 years ago

@jamesmosier your solution working for me. Thanks

MattWilliamsDev commented 5 years ago

A multi-select example would be incredibly helpful as well. Additionally, I've been hitting issues trying to get a RadioGroup with boolean values working. It's a simple Email Notifications: Enable or Disable radio group. Having an example of this would be quite helpful as well.

Andreyco commented 5 years ago

Started work on these, will provide WIP soon

Andreyco commented 5 years ago

While working on examples and with Docusaurus... It is kinda limiting but hard to imagine managing docs versioning on our own. Any plans here? Is there something better?

Edit https://www.docz.site/ but no versioning by default 😔

Andreyco commented 5 years ago

WIP and preview here https://festive-wozniak-c71293.netlify.com source here https://github.com/Andreyco/formik/tree/feature/examples/formik-examples

Andreyco commented 5 years ago

cc @demkovych - I just added radio boxes example with "check all" functionality

tkrebs2 commented 5 years ago

WIP and preview here https://festive-wozniak-c71293.netlify.com source here https://github.com/Andreyco/formik/tree/feature/examples/formik-examples

@Andreyco are there any working sandboxes floating around with current formik versions that implement radio checkbox group?

benjiwheeler commented 5 years ago

@Andreyco are there any working sandboxes floating around with current formik versions that implement radio checkbox group?

+1 on this question

viniciusdacal commented 5 years ago

Auto save form example #1506: https://codesandbox.io/s/formik-example-7fkw6

tobeycodes commented 5 years ago

I created a FormWizard that uses Yup and Hooks. Might be useful for someone here

import React, { useState, ReactElement } from 'react';
import {
  Formik,
  validateYupSchema,
  yupToFormErrors,
  FormikErrors,
  FormikValues,
  FormikActions,
} from 'formik';
import Button from '../../styles/Button';

interface MyProps {
  children: ReactElement[];
  onSubmit: CallableFunction;
  initialValues: FormikValues;
}

const FormWizard = (props: MyProps): JSX.Element => {
  const { children, onSubmit, initialValues } = props;
  const [page, setPage] = useState(0);
  const activePage = React.Children.toArray(children)[page];
  const isLastPage = page === React.Children.count(children) - 1;

  const previous = (): void => {
    setPage(Math.max(page - 1, 0));
  };

  const next = (): void => {
    setPage(Math.min(page + 1, children.length - 1));
  };

  const validate = (values: FormikValues): FormikErrors<FormikValues> => {
    if (activePage.props.validationSchema) {
      try {
        validateYupSchema(values, activePage.props.validationSchema, true);
      } catch (err) {
        return yupToFormErrors(err);
      }
    }

    return {};
  };

  const handleSubmits = (
    values: FormikValues,
    { setSubmitting }: FormikActions<FormikValues>,
  ): void => {
    if (activePage.props.onPageSubmit) {
      activePage.props.onPageSubmit();
    }
    if (isLastPage) {
      onSubmit(values);

      return;
    }

    setSubmitting(false);
    next();
  };

  return (
    <Formik
      initialValues={initialValues}
      validate={validate}
      onSubmit={handleSubmits}
      render={({ values, handleSubmit, isSubmitting }): JSX.Element => (
        <form onSubmit={handleSubmit}>
          {activePage}

          {page > 0 && (
            <Button type="button" onClick={previous}>
              Previous
            </Button>
          )}

          <Button type="submit" disabled={isSubmitting}>
            {isLastPage ? 'Submit' : 'Next'}
          </Button>

          <pre>{JSON.stringify(values, null, 2)}</pre>
        </form>
      )}
    />
  );
};

export default FormWizard;

And how a basic example of how to use it

import React from 'react';
import * as Yup from 'yup';
import { Field } from 'formik';
import FormInput from '../components/FormInput';
import FormWizard from '../components/FormWizard';

const page1ValidationSchema = Yup.object().shape({
  firstName: Yup.string()
    .email('1Email is not a valid email address')
    .required('1Email is required'),
});

const page2ValidationSchema = Yup.object().shape({
  email: Yup.string()
    .email('Email is not a valid email address')
    .required('Email is required'),
});

const Page1 = () => (
  <div>
    <div>
      <label>First Name</label>
      <Field
        name="firstName"
        component="input"
        type="text"
        placeholder="First Name"
        component={FormInput}
      />
    </div>
  </div>
);

const Page2 = () => (
  <div>
    <div>
      <label>Email</label>
      <Field
        name="email"
        component="input"
        type="text"
        placeholder="Email"
        component={FormInput}
      />
    </div>
  </div>
);

const onSubmit = (values, actions) => {
  console.log(values);
};

const onPage1Submit = () => {
  console.log('bob');
};

const InnerForm = (): JSX.Element => (
  <FormWizard
    initialValues={{
      firstName: '',
      lastName: '',
      email: '',
      favoriteColor: '',
    }}
    onSubmit={onSubmit}
  >
    <Page1
      validationSchema={page1ValidationSchema}
      onPageSubmit={onPage1Submit}
    />
    <Page2 validationSchema={page2ValidationSchema} />
  </FormWizard>
);

export default InnerForm;
Fieel commented 5 years ago

https://github.com/jaredpalmer/formik/issues/1035 has been closed even though it's not a duplicate nor resolved here, even with examples (docs would be better).

WestonThayer commented 4 years ago

Here is a simple example for a set/group of radio buttons: https://codesandbox.io/s/formik-radio-button-group-example-d6l33

vincentntang commented 4 years ago

I wrote an example using Reactstrap (UI library) with Yup + Formik, demonstrating all the important features for a wizard. Uses class components

https://github.com/vincentntang/multistep-wizard-formik-yup-reactstrap

VinothiniBalakrishnan commented 4 years ago

Here is a simple example for a set/group of radio buttons: https://codesandbox.io/s/formik-radio-button-group-example-d6l33

You did a great job. Thank you so much for your demo with radio button

patspam commented 4 years ago

Here's an updated Multistep Wizard that uses hooks, and Yup: https://codesandbox.io/s/formik-multistep-wizard-5bkkl?file=/index.js

(Evolved from @schrapel's example, updated for Formik 2.x, removed Formik internals, made more extensible, etc)

BenjDG commented 4 years ago

Some examples with fetch or http requests on submit would be helpful.

johnrom commented 4 years ago

@BenjDG there is nothing special about fetch or http requests on submit, so documenting is a little out of scope. We do document that onSubmit can be async.

Here's a fetch request and associated documentation:

<Formik 
  onSubmit={async (values) => {
    const response = await fetch(endpointUrl, { 
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: JSON.stringify(values), // or build a new FormData() for x-www-form-urlencoded
    });
    const result = response.json();

    console.log(result); // your API's response as an object
  }}
/>
BenjDG commented 4 years ago

I think some of the links in the Tutorial section point to the wrong code sandbox and it was throwing me off a bit. Thanks for your help!

johnrom commented 4 years ago

@benjdg do you know which ones? it'd be great to note them down to fix them. glad I could help!

BenjDG commented 4 years ago

At this url - https://jaredpalmer.com/formik/docs/tutorial

“You can see what we'll be building here: Final Result. “ - this links to https://codesandbox.io/s/formik-v2-tutorial-final-bq0li (when you test the form, it doesn’t work. Also, it has “lol” in the code.

johnrom commented 4 years ago

Thanks! That should have been fixed in #2484. Guess it hasn't made it to the site yet?

lsbyerley commented 4 years ago

Does anyone have an example of storing any edits made to initialValues in a separate object? Essentially this "edited" object would only store properties that differ from their respective value in initialValues. I guess this would also contain newly added or deleted values as well.

mkelley33 commented 4 years ago

Is there an example of selecting all checkboxes?

nishojib commented 4 years ago

@mkelley33

I haven't really found an example of selecting all checkboxes, so https://codesandbox.io/s/select-all-formik-lny9l this is what I have been using.

Any other solution is always welcome.

mossa-Sammer commented 4 years ago

@patspam can you explain this please, I don't see if it's using any component from Formik, as it takes Formik component props, also, typescript blaming me when I pass these props also, I changed it to use a plain div and it works, how? I don't know cc: @jaredpalmer https://github.com/formium/formik/blob/559667c823331e8be85a50e8240e45f7c782fa3c/examples/MultistepWizard.js#L76

mossa-Sammer commented 4 years ago

would love to see something official for managing multistep forms

dhlpradip commented 2 years ago

Is issue #1386 still unsolved? help needed