Git Product home page Git Product logo

form's Introduction

form's People

Contributors

aadito123 avatar ahmedbaset avatar avrahams1 avatar balastrong avatar bhattrajat avatar chibicode avatar christian24 avatar crutchcorn avatar enyelsequeira avatar escocreeks avatar fabian-hiller avatar fulopkovacs avatar gabrielmodog avatar hnq90 avatar jihchi avatar joaom00 avatar joepuzzo avatar juliendelort avatar lachlancollins avatar michaelbrusegard avatar minosss avatar nikku avatar sebastiaannijland avatar seethruhead avatar tannerlinsley avatar thg303 avatar tm1000 avatar vikaskumar89 avatar wobsoriano avatar zackderose avatar

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

form's Issues

Returns the undefined question under this.props.form.getFieldsValue ()

1. Version:

antd , 2.10.2

2. Environment:

Chrome 58 , window 10

3.What did you do?

Use this.props.form.getFieldsValue () to take the value in the form

4.The code is as follows:

import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';
const FormItem = Form.Item;
class Demo extends Component{
    handleSubmit = (e) => {
        // 阻止事件冒泡
        e.preventDefault();
        var formData = this.props.form.getFieldsValue();
        console.log(formData);
    };
    render()  {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="horizontal" onSubmit={this.handleSubmit}>
                <FormItem label="Account">
                    <Input placeholder="please input the account"
                        {...getFieldDecorator('userName')}/>
                </FormItem>
                <FormItem label="Password">
                    <Input type="password" placeholder="Please input the pasword"
                        {...getFieldDecorator('passWord')}/>
                </FormItem>
                <Button type="primary" htmlType="submit">Submit</Button>
            </Form>
        );
    }
}
export default Demo = Form.create()(Demo);

5.The result you expect is:

Use this.props.form.getFieldsValue () to take the value in the form

6.The actual result is:

qq 20170530182002

Question about dependencies

Hello good sir. Great library ;) I'm curious as to why react and react-dom are in the dependencies list? Also, why the other dependencies (except classnames)? I'm assuming you forgot to add them as dev since they're not used in the source anywhere.

Exporting buildHandler function

Does the util.js module in src/formInputs need to be exported in src/index.js to work with Custom Form Inputs? It has a buildHandler function that a Custom Form Input seems to need.

1.3.0 Rerender causes form to lose values

Hey there. 1.2.8 works great, 1.3.0 breaks all my dynamic forms. SAD.

I’ve got a bunch of user text input fields, one which causes an API call to a server to get some data. When that data comes back, an isLoading boolean is changed. Because of that, the page containing the form is re-rendered (which I can see via console.log in the render function).

The text inputs are custom FormInput components wrapped around Material UI Textfields.

Until 1.3 this was working great, however now as soon as render() is called again, my form loses all it’s values, and getValue() returns undefined for everything.

If I disable the page re-render, by not using an isLoading bool, the form retains it’s values, but then I lose all my pretty loading spinners.

I've looked through the 1.3 updates, but there's nothing immediately obvious that jumps out, any suggestions?

Any idea how to reset form state?

Hi,
I have my form populated with "values", I could clear the form values by resetting the "values" but the touched state and errors are remaining there. any idea how to reset form state completely?

Render component like this:

<UserForm values={formUser}
                onSubmit={(values) => { ... }
                resetForm={(e) => {
                  e.preventDefault()
                  this.setState({formUser: null}, () => {
                    this.setState({formUser: {name: '', password:''})
                  })
                }}
              />

The form:

...
const UserFormComponent = ({values, submitForm, resetForm, setAllTouched}) => {

  return (
    <form onSubmit={submitForm}>
...
              <div>
                <button onClick={(e) => {
                  resetForm(e)
                  loadState(null)
                  setAllTouched(false)
                }}>RESET</button>
              </div>
              <div className="col-md-1">
                <button type="submit" >SUBMIT</button>
              </div>
    </form>
  )
}

const UserForm = Form({
  validate: validateUserForm
})(UserFormComponent)

export default UserForm

validation causes bad user experience

Hello.

In your demo: https://react-form.js.org/?selectedKind=2.%20Demos&selectedStory=Kitchen%20Sink&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel if an input changes it's state from 'valid' to 'invalid' a user action is prevented.

1 click 'Email' radio button - it will be set up
2 click to 'City' input
3 click 'Text' radio button - an error for City will be display and radio button value is not changed
4 click 'Text' again - it will be chosen
5 click 'City' again and then 'Email' again - everything works as intended.

I think validation should not interrupt current user action (i.e. I should be able to select another radio button value despite the error in the City input)

How to perform async validation?

You have created an amazing form library. Thank you.

I want to integrate this into my auth-component project. I need to be able to run a validation to check if the username is available as the user is typing in the text field. Is this possible with the current API? If not, I can try to help add the feature, if you are open to it.

Improve Immutability

Aside from everything functioning great, performance and component lifecycle could be slightly improved by enforcing immutability throughout a few places. I'm open to ideas.

Error classes

Any thoughts on an option to override the default error class name? It would also be nice to be able to provide a custom class name to FormError. I'm using custom inputs to achieve this now, but it seems like a lot of extra ceremony.

Slow render speed for complex forms

I've encountered issue with pretty complex form being slow to render (because all form parts are re-rendered).

I've solved it with custom defined Inputs, where form value is stored in custom input state. Using this state I can compare it with nextState in shouldComponentUpdate.

class CustomInput extends Component {
  constructor (props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
  }

  state = { value: '' }

  shouldComponentUpdate (nextProps, nextState) {
    return this.state.value !== nextState.value
  }

  handleChange (setValue) {
    return (e) => {
      const { value } = e.target
      this.setState({ value })
      setValue(value)
    }
  }

  render () {
    return (
      <FormField field={this.props.field}>
        {
          ({ setValue, getValue, setTouched }) =>
            <input
              value={getValue()}
              onChange={this.handleChange(setValue)}
              onBlur={setTouched}
            />
        }
      </FormField>
    )
  }
}

So as you see, I need to keep internal custom form input state in sync with react-form state. And thats not the best solution in my opinion. I'm doing this because I didn't find any other way to get input value inside shouldComponentUpdate (manually passing getValue function to each input is not ideal too).

Do you have any suggestions on how to improve this case?

Could be related to #4 and #5

Multiple validation on field

I tried to apply multiple validation on field like this

        <Form
            onSubmit={(values) => {
              this.onSubmit(values)
            }}
            validate={(password}) => {
              return {
                password: !password ? 'Il campo è obbligatorio' : (password.length < 8 ? 'la password deve contenere almeno 8 caratteri' : undefined),
              }
            }}
          >{({ submitForm, getValue }) => {
            return (
             ...
            )
          }}
        </Form>

But it does not work. Can anyone help me? Thank you

silent reset

Hi,

Is it possible to add an option to resetForm to perform a silent reset?
Actually, when the form is reset, the form is validated and errors pop-out.

Promise support for onSubmit

I've put some more thought into async support and have identified another area where it would be very useful. It would be nice to have Promise support built into form.js, here: https://github.com/tannerlinsley/react-form/blob/master/src/form.js#L137

So, onSubmit could accept a function that returns a promise. We could create two lifecycle methods for handling the promise.

  • onSubmitSuccess would run if the promise resolves.
  • onSubmitError would run if the promise is rejected.

Adding promise support to onSubmit would also make it possible to support standardized error messages from the server. So the server could send back an error object with a message property that could show up in the UI, automatically.

unexpected value from getValue() in custom input example

Hello,

Here is my code, <TextField/> is from material ui. The problem is that, the input field shows the field name as default value. The behaviour of getValue(field, '') is not expected. I use getValue() || '' as a work around, which works fine.

but it would be nice to find out why the behaviour, thanks.

import { Form, FormInput } from 'react-form';
const InputField = ({field, ...rest}) => {
  return (
    <FormInput field={field}>
      {({setValue, getValue}) => {
        
        console.log(field);    /* field is 'email' */
        console.log(getValue(field, ''));   /* expect empty string on initial, but 'email' is logged */  

        return  (
          <TextField 
            value={getValue(field, '')}
            onChange={(e,v) => setValue(v)}
            {...rest} />
        )
       }}
    </FormInput>
  );
}

A Touching story

Oh hey, me again.

I believe there's an issue with Touched(), the docs say When a field is changed via setValue() or setTouched(), its corresponding field location in this object is marked as true. However, this isn't always the case, and it's messing with some error handling I'm trying to implement.

It can be shown even on the demo at http://react-form.zabapps.com/

Type "Bob" into the full name field and scroll down to the output of the "Touched" array. Don't click so the box loses focus. Touched is reporting that name has a touched status of "Bob". Now click somewhere, and the Touched status is now true.

I'm assuming that's not by design?

Should we have setValues method?

If we want to set value to multiple fields at once, we have to use setValues.

Example:

setValue('field1', value1)
setValue('field2', value1)
setValue('field3', value1)
setValue('field4', value1)
...
setValue('field99', value1)

Use setAllValues will set/replace all form values but it makes other attributes which are not in setAllValues arguments is undefined.

We can create an object which merges values from form's value with new values as:

<Form>
  {({values, setAllValues}) => {
    const profile = {
      name: 'Tanner Linsley',
      job: 'Software Developer',
      age: 27
    }
   const newValues = Object.assign({}, values, profile)
    return (
      <button onClick={() => setAllValues(newValues)}
  }}
</Form>

IMHO, it's better to have a new method setValues or setMultipleValues which doesn't override others fields' value.

Please let me know your opinion.

How to add class in your components?

Example, I want add bootstrap class to Textarea

                <Textarea
                  id="body-form"
                  field='body'
                  placeholder='bodyForm'
                 />

was id added, but how to add class?

P.S: and how to set url database, and how to POST, Update, Delete from DB?

help: calling method from `onSubmit` prop

I'm trying to create a form that clears all fields after successful running of onSubmit() but I can't figure it out.

For now I'm simulating a click on the 'Reset' button.

<Form 
  onSubmit={(values) => {
    /*Do Something*/
    if(/*success*/) {
      //Here's where I want to clear the form.
    }
  })}
>
{({submitForm, resetForm}) => {
  return(
    <form onSubmit={submitForm}>
      <Text className="" placeholder="Title" field="title" required/>
      <button type='submit'>Create Box</button>
      <button onClick={resetForm}>
        Reset
      </button>
    </form>
  );
}}
</Form>

getValue() and Controlled 3rd party components

Hi there,

I'm using the Material UI TextField component as a drop in replacement for your React Select demo and giving your library a spin. Few things that popped up that aren't necessarily anything to do with your library, but may be worthwhile thinking about :)

Here's the code:

import React from 'react'
import { FormInput } from 'react-form'
import TextField from 'material-ui/TextField';
export default ({ field, ...rest }) => {
  return (
    <FormInput field={field}>
      {({ setValue, getValue, setTouched }) => {
        return (
          <TextField
            {...rest} // Send the rest of your props to React-Select
            value={getValue() || ''} // Set the value to the forms value
            onChange={val => setValue(val.target.value) } // On Change, update the form value
            onBlur={() => setTouched()} // And the same goes for touched
            name="testext"
          />
        );
      }}
    </FormInput>
  );
}

Now, Material UI returns the event object in val. That caused an infinite loop in your removeNestedErrorValues function trying to parse that Object in return recurse(d, [].concat(_toConsumableArray(path), [i]));

Easily fixed once I figured out wtf was going on, but still, an infinite loop when passed bad data.

Secondly, I'm assuming getValue() returns undefined/null when there's no value. This causes the ol TextField is changing an uncontrolled input of type text to be controlled. error as soon as some text is entered.

Again easily fixed by the tweak above, but I'm wondering if getValue() should return '' rather than null.

Thoughts?

Manually submit form outside of <Form> component

It would be useful to call the submit and validate methods of a form while in a different component outside of the

parent. Consider the scenario when you want to have your submit form button reside in a different component hierarchy then the form.

Maybe it's already possible to do this?

Please let me know what you think, thanks.

issue with rendering components which start with lowercase

here's a sample code:

import React, { Component } from 'react';
import { Form } from 'react-form';

const foo = () => {
  return (
    <h1>FOO</h1>
  )
}

const CompanyFormComponent = () => {
  return (
    <form>
      <foo />
    </form>
  )
}

const CompanyForm = Form()(CompanyFormComponent);

export default CompanyForm;

it simply does not render the foo but when I rename the component to Foo everything works fine.
not a big deal but took me couple of hours to find it

resetForm() = this.getInitialState is not a function

Hiya, I'm using React 15.5.4 and React Form 1.2.7, and using resetForm() is now giving me this.getInitialState is not a function errors?
Happens in this area here:

 key: 'resetForm',
    value: function resetForm() {
      return this.setFormState(this.getInitialState());
    }

ResetForm not clear value of Textarea

I found a bug in the resetForm() method that does not reset Textarea value, apparently due to a missing empty string in the component getValue() method

  return _react2.default.createElement('textarea', _extends({}, rest, {
        value: getValue(), // should an empty string go here to for the method to work?
        onChange: (0, _util.buildHandler)(onChange, function (e) {
          return setValue(e.target.value, noTouch);
        }),
        onBlur: (0, _util.buildHandler)(onBlur, function () {
          return setTouched();
        })
      }));

radio buttons ?

Are there any plans to handle radio buttons?

How would you suggest handling them ?

Bug with [email protected]

I've tried to update react-form plugin to beta1, but after update, I'm receiving this error:

Warning: Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory

Uncaught TypeError: Cannot read property '__reactAutoBindPairs' of undefined

Which tracks to this line in React:

// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
  bindAutoBindMethods(this);
}

# and then here in my Component
(0, _reactForm.Form)()(FormComponentName)

Have you successfully used plugin with React 15.4.2?
Any ideas how to solve this?

UPD:

Last working version for me is 0.11.1
It seems somewhere in this commit?

cdd4bbd

Select options should have explicit value attribute

Given the following options:

const options = [{
  'label': 'A',
  'value': 'a'
}, {
  'label': 'B',
  'value': 'b'
}]

The resulting Select would look something like:

<select>
  <option value="0">A</option>
  <option value="1">B</option>
</select>

Whereas the expected and proper result looks like:

<select>
  <option value="a">A</option>
  <option value="b">B</option>
</select>

It's a very minimal alteration for which I already have a branch, and will PR momentarily.

API errors handling

Hi! Thanks for publishing your library.

So, what I can see, you have independence from state management, which is nice, also for standard inputs it is pretty declarative.

But I haven't found anything about how to fill errors from API (or just outside the form). We have such hooks inside child function, but it seems quite hacky to save such hooks to some closure and invoke later. Or maybe I just missed something?

Call validate manually

Hi,

I need the ability to call validate manually. Validation happens both locally and server side. If the server responds with errors I need to show them.

Does the api expose a way to call validate?

Missing Import RadioGroup in Annotated Example

Hi Tenner,

the annotated example needs the import RadioGroup together with Radio:
import { Form, ..., RadioGroup, Radio, ... } from 'react-form'

And in the jsx the element needs to be changed from

<radiogroup ... /> to <RadioGroup ... />.

Nice lib! Thanx

Michael

Trouble setting defaultValues for a form.

I'm writing a little shop backend using react-form and i'm struggling prefilling the form to edit existing data. I tried passing this to the form component like this

<AddEditProductForm
  onSubmit= { this.handleSubmit }
  defaultValues = {{
    name:this.props.item.name,
    color:this.props.item.color,
    …
   }}
/>

This adds the defaultValues data to the Forms props object alright, but it doesn't render in the form. What's even more confusing is: When not passing the defaultValues to the form, the props object has an empty defaultValues object. This feels like the approach i used should/could work.

When adding the defaultValues directly inside the form component it works alright, but is not dynamic.

Can anyone help me to get this fixed?
Thanks.

getInitialState on ES6 Components

So, I'm currently using warning and whenever i mount React Form i get this message:

Logged Warning

Are you guys aware of this? Apparently this library warns about getInitialState being used in a JS class, so we should set this.state on the constructor.

I can make a PR of this if has not been attacked. Thanks.

warning for React.PropTypes validation

I get this warning using it...
Warning: You are manually calling a React.PropTypes validation function for the formAPI prop on Form. This is deprecated and will not work in production with the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.

Does someone can help me with that?

Form Api - `addValue` not working as expected

Version: "react-form": "^1.2.6"

Overview

I've been referencing the annotated example as I build a form that contains a nested form. The nested form is a list of items called phonenumbers (like 'friends' in the example). Outside of the nested form is an element that uses the addValue method from the library. The goal is to use the add button to add a new item to the list which will then get rendered etc.

The issue

When I click the addValue button, it resets the value of phonenumbers instead of pushing or appending the newBasePhone object


In the following example:

  • phonenumbers is a list of objects with keys like: "value", "label", "type"
  • newBasePhone is an object like the ones in phonenumbers and has a "label" of "new"

The main form referencing the nested form and the Add button

<NestedForm
  field="phonenumbers"
>
  {SmartPhoneInput}
</NestedForm>

<ActionsWrapper>
  <Button
    type="primary"
    onClick={() => addValue('phonenumbers', newBasePhone)}
  >
    Add Number
  </Button>
</ActionsWrapper>

The SmartPhoneInput nested form spitting out just the label for now.

const SmartPhoneInput = (
  <Form>
    {({ values }) => (
      <Wrapper>
        {
          map(values, (number, index) => (
            <p>{number.label}</p>
          ))
        }
      </Wrapper>
    )}
  </Form>
);

apr-20-2017 10-53-27

Checkbox component does not handle getValue properly

I'm unable to create a controlled checkbox using any approach....
Setting the checked property does nothing.
Setting the value property does nothing.
Setting defaultChecked conflicts with controlled/uncontrolled react requirements.

The only solution I've found is modifying the source so that line 47: checked: getValue(false), is changed to checked: getValue(), and managing the Checkbox's checked prop with state and an onChange handler.

Default input value disappears on setValue(getValue())

This might be just an edge-case, not really an issue with the react-form itself. I still prefer to report this as I am not sure how can I solve it.

It seems like values provided by <Form values={} /> are not available through getValue() in FormInput on the "first run".

The input value is set to undefined when I am trying to setValue( getValue() ) in the onBlur callback without changing the input default value (it works when i change the value). I believe it should set the input value to its default value provided by <From values={ ... } /> instead of undefined.


Story:

I've created a custom input in which I verify the given value (in onBlur) and eventually change it. For example if the input value is 12 it will change to 12:00, 1:3 becomes01:30 and so on:

Custom input: <HourInput />

import moment           from "moment";
import React            from "react";
import { FormInput }    from "react-form";

export default function ( { field, isForm, ...rest } ) {
    return (
        <FormInput field={field} isForm={isForm}>
            { ( { setValue, getValue, setTouched } ) => (
                <input {...rest}
                    value={getValue()}
                    placeholder="00:00"
                    onChange={ e => setValue( e.target.value ) }
                    onBlur={ () => { setValue( verifyValue( getValue() ) ) } }
                />
            ) }
        </FormInput>
    )
}

function verifyValue( value ) {
    const time = moment( value, "HH:mm" );
    return time.isValid() ? time.format( "HH:mm" ) : "00:00";
}

I am rendering those inputs in a loop, like so:

class Foo extends Component {
    [...]

    renderHoursInputs = period => {
        const verb  = period === "start" ? "Start:" : "End:";
        const hours = MenuUtils.parseHours( RestaurantStore.data.hours );

        return (
            <tr>
                <td>{verb}</td>

                { Object.keys( hours ).map( day => (
                    <td key={`${period}_${day}`}>
                        <HourInput field={[ "hours", day, period ]} />
                    </td>
                ) ) }
            </tr>
        );
    }

    render() {
        const hours = MenuUtils.parseHours( RestaurantStore.data.hours );
        // hours = { day_index : { start : hour, end : hour }, ... ]
        // hours = { 1 : { start : "08:00", end : "16:00" }, ... }

        return (
            <Form onSubmit={...} validate={...} values={ { hours } }>
                [...]
                {this.renderHoursInputs( "start" )}
                {this.renderHoursInputs( "end" )}
                [...]
            </Form>
    }
}

The default value specified in <Form values={...} /> matches the array-like field name and is displayed correctly as you can see:

zrzut ekranu 2017-05-23 o 21 22 16

When I click on the input and change it's value, everything works correctly. The input value is changed and eventually auto-corrected as intended.

The problem appears when I click on the input and then blur it without changing anything. Then it's value is changed to 00:00 (the default one returned by verifyValue), even if the input had a default value set by the <Form />:

zrzut ekranu 2017-05-23 o 21 23 35

I've tried to use some kinds of hacks, for example hard-setting the value directly in the input, but then the input becomes controlled (?) and I cannot change it's value anymore:

// rest.value = default value
<input {...rest} value={getValue( rest.value )} />

Any thoughts on how can I solve this issue? I am not sure if I am doing something wrong or if there's a problem with the way react-form handles defaults values provided by <Form />.


Using the latest Node.js and react-form version.

Updating default values

If a form has not been changed and all values stayed default, then deafultValues of the form has changed -- shall the values in the form be updated to new defaults? If I do resetForm, all values will be reset to default, whereas I only want fields containing previous defaults to be updated to new ones.

Thanks.

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.