Giter Site home page Giter Site logo

stackworx / formik-mui Goto Github PK

View Code? Open in Web Editor NEW
968.0 12.0 141.0 12.43 MB

Bindings for using Formik with Material-UI

Home Page: https://stackworx.github.io/formik-mui

License: MIT License

JavaScript 5.41% TypeScript 94.59%
formik material-ui react

formik-mui's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formik-mui's Issues

The placeholder/label does not fill an empty multi select control

Example code

<FormControl required className={classes.formControls}>
                        <InputLabel  htmlFor="classifications-label">Classification</InputLabel>
                        <Field
                            id="assetClass"
                          //  name="assetClass"
                            label="Classification"
                            placeholder="Classification"
                            helperText="Please select classification"
                            margin="normal"
                            component={Select}
                            inputProps={{
                              name:"assetClass",
                              id: 'classifications-label',
                            }}
                        >
                          {
                          productAggregate.map(option => (
                          <MenuItem key={option.value} value={option.value}>
                            {option.value}
                          </MenuItem>
                          ))
                        }
                        </Field>
                      </FormControl>

if I change the Select Component to the materials core component. The label properly fills the empty component.

Wondering if this is a bug or I'm doing something wrong.

If you goto the materials-ui docs demo the first drop-down in the examples works perfect. If you select and unselect the items you will see the label fill the empty control.

https://material-ui.com/demos/selects/

Even in the samples that you have provided the TextFields works perfectly, but the multi select does not.

CodeSandbox is broken

The codesandbox is broken.

The fix is here:
https://codesandbox.io/s/zqwv712423
Adding a name to the select component helps
Then there's a value error in console. I've added something to remove the error, but it probably needs to be updated to a controlled value.

I didn't fix the final problem, which is there being two dropdown elements on the select:

zqwv712423_-_codesandbox

support for nested field names

When you create a nested field name (such as "user.email", "user.password" ...) it does not display the error message or put the correct styles.

Take this test in the storybook:

import React from 'react';
import Button from '@material-ui/core/Button';
import { Formik, Field, Form } from 'formik';
import { LinearProgress } from '@material-ui/core';
import { action } from '@storybook/addon-actions';
import Wrapper from './Wrapper';

import TextField from '../src/TextField';
import FormValues from './FormValues';

interface Values {
  user: {email : string};
  password: string;
}

export default () => (
  <Wrapper title="Text Field">
    <Formik
      initialValues={{ user: {email: ''}, password: '' }}
      validate={ values => {
        const errors: Partial<Values> = {};
        if (!values.user.email) {
          errors.user = {email:'Required'};
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.user.email)
        ) {
          errors.user = {email:'Invalid email address'};
        }

        if (!values.password) {
          errors.password = 'Required';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          setSubmitting(false);
          action('submit')(values);
        }, 2000);
      }}
      render={({ submitForm, isSubmitting, values }) => (
        <Form>
          <Field
            type="email"
            label="Email"
            name="user.email"
            component={TextField}
          />
          <br />
          <Field
            type="password"
            label="Password"
            name="password"
            component={TextField}
          />
          <br />
          {isSubmitting && <LinearProgress />}
          <br />
          <Button
            variant="raised"
            color="primary"
            disabled={isSubmitting}
            onClick={submitForm}
          >
            Submit
          </Button>
          <br />
          <FormValues values={values} />
        </Form>
      )}
    />
  </Wrapper>
);

I took the lodash and used the get function to solve the problem. It worked correctly, I hope you approve the pull request.

Getting a Warning when using the TextField.

Getting a warning where there is an error on the TextField.

Warning: Failed prop type: Invalid prop error of type string supplied to TextField, expected boolean.

The quick fix seems to be to set the error: showError, to be error: !!showError,.

Migrate to typescript?

Formik has better typescript support and material-ui has first-class typescript support.

Add Git Hooks

We need to add a git hook for pre commits and pre pushes so that we can format the files and update snapshots before pushing

Cannot set default value in RadioGroup

I was trying to set a default value for the radio group component but it is ignored with omit in:

import * as React from 'react';
import { RadioGroupProps as MuiRadioGroupProps } from '@material-ui/core/RadioGroup';
import { FieldProps } from 'formik';
import { Omit } from './types';
export interface RadioGroupProps extends Omit<MuiRadioGroupProps, 'name' | 'onChange' | 'value'>, FieldProps {
}
export declare const fieldToRadioGroup: ({ field, form, ...props }: RadioGroupProps) => MuiRadioGroupProps;
export declare const RadioGroup: React.ComponentType<RadioGroupProps>;

When you remove value from the omitted properties, it works as expected.
If this expected behaviour?

Question: what is the purpose of `createComponent`?

Hi Ciaran,

I'm wondering, what is the purpose of createComponent function?
It seems to be over-complicated, particularly InputComponent class component with getRenderedComponent method (which isn't used anyway).

Material UI prop "InputProps" is not supported in Formik Material UI select wrapper component

Hello,
first of all thank you for the work on this project ๐Ÿฅ‡ . With TextFields everything is working fine ๐Ÿ‘ .

I am currently trying to use the Select wrapper component of this repository, but the documentation of this feature is not so much. At least one prop which the official Material UI component TextField, in context of select, supports is currently not working. This acccounts especially for the prop "InputProps" which makes the component able to display icons inside the select. In addition, I don't understand why the label is not being displayed. Before I created this issue, I was looking at your stories and source code but couldn't determine what I might have done wrong.

To illustrate , I created a short example on CodeSandBox:

I would appreciate a short feedback. Thanks in advance.

Select multiple schema errors

Hello,

It is not showing schema errors with select multiple on form submit.
<FormControl fullWidth> <InputLabel htmlFor="tags">Tags</InputLabel> <Field type={"text"} name="tags" component={Select} multiple={true} inputProps={{ name: 'tags', id: 'tags', }} fullWidth > <MenuItem value="dogs">Dogs</MenuItem> <MenuItem value="cats">Cats</MenuItem> <MenuItem value="rats">Rats</MenuItem> <MenuItem value="snakes">Snakes</MenuItem> </Field> </FormControl>

[Typescript] Cannot find module 'formik-material-ui'

Typescript can't find any type definitions when trying to import the library. The example provided on the github page in codesandbox shows error on lines

import {TextFieldProps} from 'formik-material-ui/TextField';
import {fieldToTextField, TextField} from 'formik-material-ui';

which says Cannot find module....

I am guessing this is because the file with typings is called main.d.ts when it should be index.d.ts, but I might be wrong ;)
Is it possible to fix it? Thanks.

Field height jumps when errors appear because of `helperText`

Same issue as here.

A field without error and warning has no helperText set. In that case, material-ui's will not reserve any space for the helper text. When the field becomes validated and is invalid, the errorText is added and the height of the field increases. This leads to a visible jump in the page layout, which is especially bad if there are many invalid fields, or if it happens often as users click through the fields.

To reproduce in the demo linked from the main page, just focus and unfocus the "Email" field and watch the remainder of the form move down.

Any proper solution will have to reserve this space always, even when no error message is present. This leads to a less dense form. In my opinion/application, the errorText space is just enough to make the form appear nice when there are no errors, i.e. I don't have to code any padding/margin etc. When an error does appear, it comes quite close to the field just below, but I prefer that over the visual jump.

If you're willing to change the default behavior of formik-material-ui, I'm happy to send a PR that implements this fix (similar to this).

Formik material-ui doesn't link to react state in component

Big fan,

When we get/set the state with a Formik field, we'd expect to be able to do so within the component itself.

This is how it works with formik itself. However, it doesn't work with the text, switch, or select component.

Here's the difference as a code sandbox demo

Trying to do so results in the following error:

Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components

Create Switch

Create Switch

  • Create Component
  • Jest Test
  • Create Story

Select with multiple is not Working

Material-UI: the value property must be an array when using the Select component with `multiple

<Field
name='events'
component={Select}
multiple
value={["a", "b"]
onChange={this.handleChange}>






Runtime error with Checkbox and Material-UI v4

Just a heads-up. This may be due to changes in Material-UI v4 alpha.

The following:

<Field
  Label={{ label: 'Do you confirm?" }}
  name='confirmation'
  component={CheckboxWithLabel}
  color='primary'
/>

At runtime was causing:

Warning: Failed prop type: Invalid prop `checked` of type `string` supplied to `ForwardRef(Checkbox)`, expected `boolean`.
    in ForwardRef(Checkbox) (created by WithStyles(ForwardRef(Checkbox)))
    in WithStyles(ForwardRef(Checkbox)) (created by FormikMaterialUICheckboxWithLabel)
    in label (created by ForwardRef(FormControlLabel))
    in ForwardRef(FormControlLabel) (created by Context.Consumer)
    in WithFormControlContext(ForwardRef(FormControlLabel)) (created by WithStyles(WithFormControlContext(ForwardRef(FormControlLabel))))
    in WithStyles(WithFormControlContext(ForwardRef(FormControlLabel))) (created by FormikMaterialUICheckboxWithLabel)

Changing this:

https://github.com/stackworx/formik-material-ui/blob/8d8b6abf18e6ce9f95020eb6f9ce9f9c6b6b8e10/src/Checkbox.tsx#L26

To:

    checked: field.value

That is, leaving the boolean value alone, not converting it to string, fixed it.

Error message is shown as helperText even when TextField is not touched yet

Hi,
I just came across your library and noticed potentially unwanted behavior of TextField component.

Steps to reproduce:

  1. Open https://codesandbox.io/s/z65oq5q9y3
  2. Type few letters in email TextField (so the email is not valid)
  3. See helperText. Note, that this field is not highlighted with error color yet

Current behavior:

Error message appears instead of helperText

textfield

Expected behavior:

While field is not touched, there should be no error message in helperText.

Rationale:

User can pass custom helperText. For example, for email field it can be helperText="e.g. [email protected]".

This helperText should be overridden by error message only when field is touched, so user can always see helperText while typing the first time.

Let me know what do you think about that.
I'll submit a PR if you agree ;)

[typescript] Cannot use TextField as a child of Field

Hi, in KitchenSink.story.tsx and other examples TextField is passed as a value of component-property:

<Field type="email" label="Email" name="email" component={TextField} />

I would like to use TextField as a child of Field, because then its properties should be recognized by the compiler, as they have a concrete type, unlike any in case of Field:

<Field name="email">
    {(fieldProps: FieldProps) => (
        <TextField {...fieldProps} type="email" label="Email" />
    )}
</Field>

If I make this change, then it produces following error:

Error:(57, 24) TS2740: Type '{ type: string; label: string; field: { onChange: (e: ChangeEvent<any>) => void; onBlur: (e: any) => void; value: any; name: string; }; form: FormikProps<any>; }' is missing the following properties from type 'TextFieldProps': style, classes, innerRef, className, and 7 more.

Follwing changes seem to fix it (and don't brake any tests):

  • in TextField.tsx change TextFieldProps from interface to a type:
export type TextFieldProps = FieldProps & Omit<MuiTextFieldProps, 'error' | 'name' | 'onChange' | 'value'>
  • in types.ts change the definition of Omit to the one implemented by material-ui project:
export type Omit<T, K extends keyof any> = T extends any ? Pick<T, Exclude<keyof T, K>> : never;

With this solution the properties of Material-UI's TextField get recognized and I get Intellisense support from my IDE. I suspect similar problem can have another components, but I haven't time to test it. The solution used in storybook, when the component is passed as a prop, is shorter, but then the component's props are not type checked.

TextField is not reset when using handleReset

Hello,

When using the handleReset function of Formik, the value property of <input> element is emptied but the <TextField> value remains.

<Formik render={({handleReset}) => (
  <Form>
    <Field name='name' component={TextField} label='Test' />
  </Form>
  <Button onClick={handleReset}>Reset</Button>
  )}
/>

Kind regards,
Sam

Create Kitchen Sink

Create Full Kitchen Sink Example.

It should contain at least one of every component. Some interactions between them and at least one Formik Field Array example

Errors not shown if field hasn't be touched on form submission

Hi !

I'm creating a "sign in" form and I noticed that if I submit the form without touching any fields, no errors are shown ... It's because of this line : https://github.com/stackworx/formik-material-ui/blob/8d8b6abf18e6ce9f95020eb6f9ce9f9c6b6b8e10/src/TextField.tsx#L23

If the field is "pristine" the lib doesn't show the error message, even after a submission.

It would be nice if the lib could display errors during submission even if the fields are pristine

Labels and initial values overlap

we are using Query component to fetch details and populating initialvalues, all the values are being set but
the labels (which are displayed as placeholders before entering any values) remain same.

That is both labels and initial values are overlapping in the text field.

we have supplied enablereinitialize flag also.

Getting a warning when using TextField

Hello,

When using the TextField in the last version, I am getting the following warning:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

Versions:

"react": "^16.5.2",
"@material-ui/core": "^3.4.0",
"formik-material-ui": "^0.0.14"

How to create a custom file Upload without typescript?

import { SimpleFileUpload, SimpleFileUploadProps } from "formik-material-ui";

CustomFileUpload = (SimpleFileUploadProps) => (
    <FormControl>
      {SimpleFileUploadProps.label && (
        <InputLabel shrink error={!!SimpleFileUploadProps.form.error}>
          {SimpleFileUploadProps.label}
        </InputLabel>
      )}
      <Input
        error={!!SimpleFileUploadProps.form.error}
        inputProps={{
          type: 'file',
          disabled: SimpleFileUploadProps.disabled || SimpleFileUploadProps.form.isSubmitting,
          name: SimpleFileUploadProps.field.name,
          onChange: (event) => {
            const file = event.currentTarget.files[0];
            SimpleFileUploadProps.form.setFieldValue(SimpleFileUploadProps.field.name, file);
          },
        }}
      />
      {SimpleFileUploadProps.form.error && (
        <FormHelperText error>{SimpleFileUploadProps.form.error}</FormHelperText>
      )}
    </FormControl>
  )

I tried using the above snippet, but no luck :(

Code Sandbox on npm page doesn't work

https://www.npmjs.com/package/formik-material-ui contains a link to Code Sandbox at https://codesandbox.io/s/m56kj105n8 which gives:

Invariant Violation
Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
    in p (created by FormHelperText)
    in FormHelperText (created by WithStyles(FormHelperText))
    in WithStyles(FormHelperText) (created by TextField)
    in div (created by FormControl)
    in FormControl (created by WithStyles(FormControl))
    in WithStyles(FormControl) (created by TextField)
    in TextField (created by FormikMaterialUITextField)
    in FormikMaterialUITextField (created by FieldInner)
    in FieldInner (created by Context.Consumer)
    in C (created by Formik)
    in form
    in Unknown (created by Context.Consumer)
    in Form (created by Formik)
    in Formik (created by App)
    in App

which is a bit unfortunate as (I believe) formik-material-ui is exactly the library I'm looking for.

It appears to be caused by:

<Field select label="With Select" component={TextField}>
     <div>Test</div>
</Field>

If I add a 'name=' property to Field, it renders.

Select with value="" doesn't show MenuItem

If you have a Field with Select component and this MenuItem displays blank instead of None.

<MenuItem value="">None</MenuItem>

Run the sandbox below and change the Select from Two to None and you'll see nothing is displayed.

Edit Formik MUI Blank Select Value

How to configure TextField?

Hello,

i want to use some TextField parameters such as variant="outlined", fullwidth etc.. How to configure that?

Label in CheckboxWithLabel.d.ts

Hi,
I am trying to do something like this with Formik and mui:

<Field type="checkbox" name="check" id="checkA" component={MuiCheckbox} value={values.someValue} label="some label" />

`const MuiCheckbox = (props: CheckboxWithLabelProps) => (

{props.label}
);`

but props.label is giving me a type error: Property 'label' does not exist on type 'CheckboxWithLabelProps'. Did you mean 'Label'?

I checked CheckboxWithLabel.d.ts and it shows that label is defined as (Label):

export interface CheckboxWithLabelProps extends CheckboxProps { Label: Omit< MuiFormControlLabelProps, 'checked' | 'name' | 'onChange' | 'value' | 'inputRef'>;}

I was able to eliminate the error by changing {props.label} to {props.Label} and change (label="some label" prop in to Label="some label", or by changing the Label to label in CheckboxWithLabel.d.ts.

Is there something I am missing or doing wrong here? Is CheckboxWithLabelProps even the right type to use in this case?

I am using formik-material-ui ver 0.0.16

Thanks in advance

Create Login Form Sample

Create a Login Form Sample

It should have a username and password field.
Both fields are required.

The username must have minimum length 6 and the password must have minimum length 6 and contain numbers.

It should have 2 buttons, submit and reset

CheckBoxLabel does not report validation error

I forked the code sandbox from the readme at https://codesandbox.io/s/6lpkp0m00z and added a checkbox which is required to be true:

        <Field
          type="checkbox"
          name="accept"
          Label={{label: 'Accept privacy policy'}}
          component={CheckboxWithLabel}
        />

And:

    validate={values => {
      const errors: {email?: string; accept?: string} = {};
      // ...email validation...
      if (!values.accept) {
        errors.accept = 'Required';
      }
      return errors;
    }}

If I click submit on the empty form, the email text field gets highlighted in red and marked Required. The accept checkbox field stays unchanged, no error is shown.

Switch initially checked

Given the following truncated example, I would expect the switch to be initially turned on:

import { Switch } from 'formik-material-ui';

initialValues = { myField: true }

<FormControlLabel
	control={<Field name="myField" type="checkbox" component={Switch} />}
	label="My Field"
/>

I noticed issue #41 and PR #42 but couldn't get it to work out of the box.

I added some logs to the Switch component, and noticed that field.value === undefined. So I added value={values.myField} as a prop to the Field, and it works now. Not sure if this is how it's supposed to work.

Working version:

<Formik render={({ values }) =>
    <form>
        <FormControlLabel
            control={<Field name="myField" value={values.myField} type="checkbox" component={Switch} />}
            label="My Field"
        />
    </form>
</Formik>

versions:

Disabled property is not propagated

Hi there,

if the disabled property is passed to a component, the value is ignored as only isSubmitting is taken into consideration.

See this snippet:

  ({ field, form: { isSubmitting }, ...props }) => ({
    disabled: isSubmitting,

Therefore it is impossible to disable a component by hand.

OnChange is not triggered in Select component?

Hello There,

I tried to use the Select component from "formik-material-ui" wrapped inside my custom component, however, the onChange event wasn't triggered when I added to the component.

The code is as simple as follows:

    const handleChange = (x, y) => {
      console.log(x, y);  // Never called.
    };

    return (<Select {...props} onChange={handleChange} />);

I'm pretty new to react, formik, and material-ui. Any idea what I've done wrong? Is there any other attribute I need to set?

Thanks in Advance,
~ John

Code Sandbox in README fails

From Console:

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
    in p (created by FormHelperText)

    in FormHelperText (created by WithStyles(FormHelperText))

    in WithStyles(FormHelperText) (created by TextField)

    in div (created by FormControl)

    in FormControl (created by WithStyles(FormControl))

    in WithStyles(FormControl) (created by TextField)

    in TextField (created by FormikMaterialUITextField)

    in FormikMaterialUITextField (created by FieldInner)

    in FieldInner (created by Context.Consumer)

    in C (created by Formik)

    in form

    in Unknown (created by Context.Consumer)

    in Form (created by Formik)

    in Formik (created by App)

    in App```

Allow default `onChange` to be overridden

Is there a way to override the contained input's onChange handler?

I would like to do something like the following...

import { TextField } from 'formik-material-ui'

<Formik
  render={({ handleChange }) => (
    ...
    <Field
      label="Email"
      name="email"
      type="email"
      component={TextField}
      onChange={e => {
        // Call the default handler...
        handleChange(e)
        // Then do something custom...
      }}
    />
    ...
  )
/>

From what I gather, the field's default onChange always takes precedence.

Is this currently possible, and if so, is there a recommended way to do this?

Thanks!

Add semantic release

Because life is too short to deploy by hand

  • Auto Changelog
  • Semantic release
  • Github Releases
  • Npm Publish

The default semantic-release config has a pretty stringent commit format that I don't really want to enforce for contributors

Create Select

Create Select

  • Create Component
  • Jest Test
  • Create Story

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.