Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Examples / Sandboxes #1315

Open
4 of 10 tasks
jaredpalmer opened this issue Feb 7, 2019 · 30 comments
Open
4 of 10 tasks

New Examples / Sandboxes #1315

jaredpalmer opened this issue Feb 7, 2019 · 30 comments

Comments

@jaredpalmer
Copy link
Owner

jaredpalmer commented Feb 7, 2019

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

Nice to have

@EfstathiadisDimitris
Copy link

EfstathiadisDimitris commented Feb 9, 2019

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
Copy link

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
Copy link
Contributor

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
Copy link

@jamesmosier your solution working for me. Thanks

@MattWilliamsDev
Copy link

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
Copy link
Collaborator

Started work on these, will provide WIP soon

@Andreyco Andreyco self-assigned this May 21, 2019
@Andreyco
Copy link
Collaborator

Andreyco commented May 22, 2019

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
Copy link
Collaborator

Andreyco commented May 26, 2019

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

@Andreyco
Copy link
Collaborator

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

@johnrom johnrom removed the v2 label May 27, 2019
@johnrom johnrom added this to the v2.0 milestone May 27, 2019
@tkrebs2
Copy link

tkrebs2 commented Jun 25, 2019

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
Copy link

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

+1 on this question

@viniciusdacal
Copy link
Contributor

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

@tobeycodes
Copy link

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
Copy link

Fieel commented Oct 7, 2019

#1035 has been closed even though it's not a duplicate nor resolved here, even with examples (docs would be better).

@stale stale bot removed the stale label Oct 7, 2019
@WestonThayer
Copy link

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

@vincentntang
Copy link

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

@stale stale bot added the stale label Jan 24, 2020
@VinothiniBalakrishnan
Copy link

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

@stale stale bot removed the stale label Apr 9, 2020
@patspam
Copy link
Contributor

patspam commented May 6, 2020

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
Copy link

BenjDG commented May 29, 2020

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

@johnrom
Copy link
Collaborator

johnrom commented May 29, 2020

@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
Copy link

BenjDG commented May 30, 2020

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
Copy link
Collaborator

johnrom commented May 30, 2020

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

@BenjDG
Copy link

BenjDG commented May 30, 2020

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
Copy link
Collaborator

johnrom commented May 31, 2020

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

@lsbyerley
Copy link

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
Copy link

Is there an example of selecting all checkboxes?

@nishojib
Copy link

@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
Copy link

mossa-Sammer commented Oct 21, 2020

@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
Copy link

would love to see something official for managing multistep forms

@jaredpalmer jaredpalmer unpinned this issue Nov 9, 2020
@dhlpradip
Copy link

Is issue #1386 still unsolved? help needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests