Giter Club home page Giter Club logo

react-redux-form's Introduction

React Redux Form

Join the chat at https://gitter.im/react-redux-form/Lobby Build Status npm version CDNJS

⚠️ This project is in maintenance mode only. Please consider using Formik instead.

React Redux Form is a collection of reducer creators and action creators that make implementing even the most complex and custom forms with React and Redux simple and performant.

npm install react-redux-form@latest --save

Installation

# Dependencies (you probably already have these)
npm install react react-dom redux react-redux --save

# version 1.x.x
npm install react-redux-form@latest --save

Zero-Boilerplate <LocalForm>

If you want to get up and running with forms quickly without having to set up Redux, just use Local Forms:

import React from 'react';
import { LocalForm, Control } from 'react-redux-form';

export default class MyApp extends React.Component {
  handleChange(values) { ... }
  handleUpdate(form) { ... }
  handleSubmit(values) { ... }
  render() {
    return (
      <LocalForm
        onUpdate={(form) => this.handleUpdate(form)}
        onChange={(values) => this.handleChange(values)}
        onSubmit={(values) => this.handleSubmit(values)}
      >
        <Control.text model=".username" />
        <Control.text model=".password" />
      </LocalForm>
    );
  }
}

That's all you need. Seriously. Read the Documentation for more information.

NOTE: Please use <LocalForm> with react-redux version 4.x.x or 5.x.x.

Quick Start

For more fine-grained control (such as using custom reducers, storing form state globally, dispatching actions, etc.), you'll want to set up a Redux store for your forms.

Be sure to read the step-by-step quick start guide in the documentation.

import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { combineForms } from 'react-redux-form';

import MyForm from './components/my-form-component';

const initialUser = { name: '' };

const store = createStore(combineForms({
  user: initialUser,
}));

class App extends React.Component {
  render() {
    return (
      <Provider store={ store }>
        <MyForm />
      </Provider>
    );
  }
}
// ./components/my-form-component.js'
import React from 'react';
import { connect } from 'react-redux';
import { Control, Form } from 'react-redux-form';

class MyForm extends React.Component {
  handleSubmit(val) {
    // Do anything you want with the form value
    console.log(val);
  }

  render() {
    return (
      <Form model="user" onSubmit={(val) => this.handleSubmit(val)}>
        <label>Your name?</label>
        <Control.text model=".name" />
        <button>Submit!</button>
      </Form>
    );
  }
}

// No need to connect()!
export default MyForm;

Posting Issues

When posting an issue, please include a detailed description along with a relevant code sample. Attaching a failing test case with your issue will go a long way and is much appreciated.

Feel free to fork this CodePen or this CodeSandbox for quickly creating reproducible examples!

react-redux-form's People

Contributors

andrewhl avatar andrewmtam avatar antonvasin avatar asvetliakov avatar brycesenz avatar chrisblossom avatar danielericlee avatar davidkpiano avatar deptno avatar dreid avatar etrepum avatar galkinrost avatar greenkeeperio-bot avatar hsrobflavorus avatar kabbi avatar lasergoat avatar maludwig avatar marcinm2h avatar mdgbayly avatar mfal avatar nigredo-tori avatar peterox avatar psykar avatar romseguy avatar sl33kr avatar tiagoefmoraes avatar tonaphone avatar ulricgan avatar valoricde avatar zach-waggoner 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  avatar

react-redux-form's Issues

FieldComponent doesn`t override defaultProps

Problem raise then a wrote a wrapper for react-select.

export const SelectField = createFieldClass({
    'Select': props => ({
        onChange: () => console.log('CHANGE')
        value: props.modelValue
    })
});

<SelectField model={`${field}.classes`}>
  <Select options={CLASSES}/>
</SelectField>

onChange never get called, because react-select set onChange to undefined by default, and it doesnt get overrided.

May be provided props must be more prioritized over component props?

  render() {
    const { control } = this.props;

    return cloneElement(
      control, {
-        ...this.props,
-        ...control.props,
+        ...control.props,
+        ...this.props,
      });
  }

Validation not working

Hi David,
Thanks for your great module :-) I'm having trouble getting the validation working. I'm attaching 2 working examples, in both examples data is stored in Redux correctly even for the React-Bootstrap Input component, I've added some validation methods that are called on the onBlur of the Firstname field:
Example 1 - REACT-REDUX-FORM
I can see the validation methods are called on the onBlur because they write some log messages but I do not get the required error message 'First Name is required' displayed on the screen even though I can see in Redux that an error does exist for the firstName required validation check.

Example 2 - REACT-REDUX-FORM_BOOTSTRAP
In this example the validation routines do not even get executed on the React-Bootstrap Input component but Redux is still being updated correctly when you change the value in the field so that part is working for a custom component but the validation functions are not being called.

Just unzip the attached file and then do an npm install followed by npm start on each example and access them in your browser at localhost:3000

More than likely it is something I'm doing wrong :-(

Cheers,
Paul
Validation-problem-examples.zip

default settings for Field

i would like to set default settings for all fields at form. E.g.: validateOn, validators and etc.

<form validators={..} validateOn=...>

with respecting individual settings for field.

In that case it will be possible to move validating code outside form, right now its not so nice - a lot of to repeat.

How to get the right index for array model?

const users = [{ name: 'Brad Pitt' }, { name: 'Bruce Wayne' }];

// UserDetails.js
const UserDetails = ({ user }) => (
  <Field model="users[??].name">
    <input value={user.name} />
  </Field>
);

The question is how do I fill the index inside the <Field model ... > ??

react-redux-form vs redux-form

Hey, what is the general difference of this library and redux-form?
What should I think about when I make a decision?
I can determinate a litte by myself, such as this separates model from form, but I need more official info.
Cheers!

[PROPOSAL] Form state shape

It seems that grabbing a field from the form state is a bit tedious, especially if you have to do something like userForm.fields['foo.bar.baz'].pristine, etc.

So, every field, regardless of how deep it is, needs to make these fields available:

const initialFieldState = {
  blur: true,
  dirty: false,
  focus: false,
  pending: false,
  pristine: true,
  submitted: false,
  touched: false,
  untouched: true,
  valid: true,
  validating: false,
  viewValue: null,
  validity: {},
  errors: {},
};

And the current shape of the form state is this:

const formShape = {
  ...initialFieldState,
  fields: {
    'foo': { ...initialFieldState },
    'foo.bar.baz': { ...initialFieldState },
  }
}
// ...etc.

Proposal(s)

Let's find an easier way to both maintain the shape of the original model shape, and easily grab the relevant form/field states for each field (and form). Here's an initial suggestion, taking cues from how Angular does its forms:

formShape = {
  foo: {
    bar: { ... }
    $field: { ...initialFieldState }
  },
  $field: { ...initialFieldState }
}

So that fields can be accessed as if it were the original model, with the special $field key containing the entire state of the field, like userForm.foo.bar.$field.errors.

Any other suggestions? What is easiest for everyone?

please give more examples

i'm quite new at field of react and redux, but i already like your implementation. But can you write more examples? Not like 'snapshots' of code, but full version? For example at your site there is only 'demo' for validating on submit - without any code. And i would like to connect the dots - see at least one full version of example - like small app. It would help a lot.

p.s.: i like that your library do only one thing, like https://github.com/callum/redux-routing - just routing, that also can work without react.

Trigger validation from an action

I have noticed that validation does not fire for fields updated via actions.change

Also, is it possible to trigger the validation from an action, without repeating all the validation logic in the action?

Hopefully I'm not missing something obvious, I've been trying to work out how I could do it.

!) Repeat validation logic in page and in action

  1. Move all validation into an action and then trigger the action for all fields blur events.

Thanks

Field's change visually when Chrome's autofill kicks in

In the following image, you see the address field looks odd. It originally looked like the others when the page loaded and then changed to this after a second -- it seemed to be related to LastPass adding it's little autofill icon there. This is in the Autofill Fields recipe in the documentation.
image

The input looks like this in Chrome dev tools

<input type="text" name="order.billing.address" data-reactid=".0.1.0.0.0.1:1.$/=11" style="background-image: url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHklEQVQ4EaVTO26DQBD1ohQWaS2lg9JybZ+AK7hNwx2oIoVf4UPQ0Lj1FdKktevIpel8AKNUkDcWMxpgSaIEaTVv3sx7uztiTdu2s/98DywOw3Dued4Who/M2aIx5lZV1aEsy0+qiwHELyi+Ytl0PQ69SxAxkWIA4RMRTdNsKE59juMcuZd6xIAFeZ6fGCdJ8kY4y7KAuTRNGd7jyEBXsdOPE3a0QGPsniOnnYMO67LgSQN9T41F2QGrQRRFCwyzoIF2qyBuKKbcOgPXdVeY9rMWgNsjf9ccYesJhk3f5dYT1HX9gR0LLQR30TnjkUEcx2uIuS4RnI+aj6sJR0AM8AaumPaM/rRehyWhXqbFAA9kh3/8/NvHxAYGAsZ/il8IalkCLBfNVAAAAABJRU5ErkJggg==&quot;);background-attachment: scroll;background-size: 16px 18px;background-position: 98% 50%;background-repeat: no-repeat;">

Compared to the other input that looks fine:
<input type="text" name="order.billing.city" data-reactid=".0.1.0.0.0.1:2.$/=11">

The style attribute I believe is added by LastPass's autofill; removing it fixes the appearence which then causes the following style to apply to the input because of the "not([style])" selector

image

Seems like it's simply not a good idea to use CSS selectors that say "not([style])" for this reason; I'm not sure why that particular selector is included though, nor the effects of removing it.

FieldActions Validate is not processed

Hi,

We have a form distributed over different components:

<MyForm>
  <Step1 model={userModel} formModel={userFormModel} />
  <Step2 model={userModel} formModel={userFormModel} />
  <Step3 model={userModel} formModel={userFormModel} />
</MyForm>

...

const mapStateToProps = (state) => ({
  steps: state.register.steps,
  userModel: state.register.user,
  userFormModel: state.register.userFormModel
});

The steps are arranged in an accordion, so the user would be able to skip steps. However in the end, when the user clicks the submit button all fields should be validated. I tried to send

onSubmit() {
    this.props.validate('register.user.name');
    this.props.validate('register.user.age');
}

But no validators were triggered. The other options I could think of were

  • duplicating the validators and check them in the top component as well
  • check if userFormModel contains the entry key and then check the validity

What would be a good way to do this?

Control rendering of `Field` container element

Field is trying to be smart and render container element only when there is more than one child element. I'd like it to be even smarter and also render container element for cases where we've already assigned some other properties to it (for instance className or id).

<Field model="filter.email" className="field six wide">
    <input type="text" placeholder="E-mail" />
</Field>

Current output (className is lost):

<input type="text" placeholder="E-mail" name="filter.email" data-reactid=".0.0.0">

Expected output:

<div class="field six wide" data-reactid=".0.0.0">
    <input type="text" placeholder="E-mail" name="filter.email" data-reactid=".0.0.0.$/=11">
</div>

[PROPOSAL] Form states

There is a lot of confusion about form states.
I propose we remove extraneous fields and change behavior as expected by the questions below

.blur

Opposite of focus? **extraneous (also I don't think this works)
Remove.

.dirty

Did the user change initial state?
initial: false
field: Change to true there has been any changes to the field.
form: Change to true if there has been any changes to any fields inside that form.

.focus

Is the user currently highlighting the field/form?
initial: false
field: True when the user is currently interacting with the field, false otherwise.
form: True when the user is interacting with any part of the form, false otherwise.

.pending

Did the user submit and is the onSubmit handler currently running?
initial: false
field: Equal to form's value when updated, not created. (Dynamic fields)
form: True only when the onSubmit handler has been called, false once it has been completed. Validity not taken into consideration.

.pristine

opposite of dirty? **extraneous
Remove.

.submitted

Did the user submit the form?
initial: false
field: Equal to form's value when updated, not created. (Dynamic fields)
form: True only when the onSubmit handler has been called. Field/form validity not taken into consideration.

.touched

Did the user interact with the field/form?
initial: false
field: True once the user clicks the field.
form: True once the user clicks any field in the form.

.untouched

Opposite of touched? **extraneous
Remove.

.valid

Is the field/form valid?
initial: true (assuming no validation/everything passes)
field: false when fails valid/error checks, true when passes
form: false when any field fails valid/error checks, true when all fields pass

.validating

Is the field/form being validated (includes checking for errors)?
initial: false
field: true when validation is occurring
form: true when any field is validating

.viewValue

No idea? **extraneous?
Remove.

.validity

Is the field/form valid?
initial: null
field: Field specific validation checks
form: Form as whole validation checks

I think this should be removed and merged with errors. And then you ask the question, is the field/form invalid? Simplifies and shrinks API.

.errors

If any, what are the errors?
initial: null
field: Field specific error checks
form: Form as whole error checks

.fields

What are the available fields?
initial: null (if no initial fields specified)
field: Sub-fields? No idea about this one.
form: Current fields.

See also #56.

Possibly add

.validSubmit

Did the user submit the form and was it successful?
initial: false
field: Equal to form's value when updated, not created. (Dynamic fields)
form: True when the onSubmit handler has been and successfully passed checks.

React Native requires Babel devDependencies

Hey, thanks for this lib! I'm excited to start building with it — on first glance it looks like exactly what I'm after 😀.

I'm using React Native and noticed that I needed to install the following devDependencies in order to get react-redux-form to compile:

    "babel-core": "^6.3.17",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",

This is my first foray into RN, so I'm not sure how its Babel compiler works in cases like these. Should this be a necessary step for using react-redux-form with RN, or is there a better way I'm overlooking?

Bundle size discussion

Currently react-redux-form has quite a large bundle size.

Using a Webpack production setup, ran the results though gzip-size, pretty-bytes, and webpack-bundle-size-analyzer get the following results. (granted I could be doing something drastically wrong)

Before react-redux-form:
Info: main-a7e6efc158923f542641.js 236.19 kB (~65.99 kB gzipped)
lodash: 2.8 KB (0.326%)

After react-redux-form
Info: main-2baf2fc84daf142ae6da.js 291.89 kB (~82.07 kB gzipped)

~16.08 kB gzipped added.

According to my tests below, lodash is currently accounting for ~8.46 kB, a little more than half.

I think we should start removing as much of lodash as we can.

Below are my results sorted in lodash function size.

initial:
Info: Client Assets:
Info:   main.js 528 B (~325 B gzipped)

import _ lodash:
Info:   main.js 62.72 kB (~22.13 kB gzipped)

import mapValues from 'lodash/mapValues';
import partial from 'lodash/partial';
import isEqual from 'lodash/isEqual';
import endsWith from 'lodash/endsWith';
import capitalize from 'lodash/capitalize';
import _get from 'lodash/get';
import toPath from 'lodash/toPath';
import isPlainObject from 'lodash/isPlainObject';
import isBoolean from 'lodash/isBoolean';
import identity from 'lodash/identity';
Info:   main.js 26.8 kB (~8.46 kB gzipped)
lodash: 120.32 KB (97.4%)

import mapValues from 'lodash/mapValues';
Info:   main.js 16.09 kB (~4.92 kB gzipped)
lodash: 68.35 KB (97.5%)

import partial from 'lodash/partial';
Info:   main.js 10.61 kB (~3.94 kB gzipped)
lodash: 50.61 KB (96.1%)

import isEqual from 'lodash/isEqual';
Info:   main.js 12.05 kB (~3.77 kB gzipped)
lodash: 49.29 KB (97.5%)

import endsWith from 'lodash/endsWith';
Info:   main.js 2.89 kB (~1.22 kB gzipped)
lodash: 10.05 KB (90.1%)

import capitalize from 'lodash/capitalize';
Info:   main.js 2.73 kB (~1.17 kB gzipped)
lodash: 7.94 KB (85.2%)

import _get from 'lodash/get';
Info:   main.js 2.63 kB (~1.13 kB gzipped)
lodash: 8.03 KB (77.8%)

import toPath from 'lodash/toPath';
Info:   main.js 2.26 kB (~1 kB gzipped)
lodash: 6.72 KB (73.9%)

import isPlainObject from 'lodash/isPlainObject';
Info:   main.js 1.22 kB (~589 B gzipped)
lodash: 2.8 KB (57.6%)

import isBoolean from 'lodash/isBoolean';
Info:   main.js 890 B (~454 B gzipped)
lodash: 1.46 KB (43.5%)

import identity from 'lodash/identity';
Info:   main.js 743 B (~391 B gzipped)
lodash: 349 B (21.1%)

Thoughts? Are others seeing this kind of bundle increase?

Repo readme / NPM release / current status?

This looks interesting. However, it's a bit hard to check it out right now, because the only NPM release appears to be out-of-date, and there's no readme. I do see that you've got actual documentation on GH Pages, which is certainly a plus. What's the current status of this library?

Add a recipe for 'modeled' reducer enhancer

Can you add a recipe for using the modeled reducer enhancer? The doc is a little too bare bones for that right now - in particular, how does one give it an initial state like you can with createModelReducer()?

(I know I can dig through the source, but I'm kinda fatigued from.. having to dig into the source in lieu of docs for a lot of the 3rd party modules that I'm using. The docs are pretty awesome otherwise though!)

confused about custom controls

I'm confused about how to use custom controls in a really simple case. My controls use the standard props onChange and value, so I don't think I should need to do any special mapping. But I'm still not sure what I am supposed to do.

I looked a little at the source, but I am still confused. One thing I wondered about is why the Control component specifies that modelValue should be a string in its propTypes -- couldn't it be anything?

Here is a simplified version of one of my controls (not tested). The real control does some validation and normalization (some of which React Redux Form could help with, but I prefer to do it in my custom controls, let's say).

class DayAndMonthInput extends Component {

    render() {

        const {onChange, value} = this.props

        return (
            <div>
                <input type="text"
                       onChange={e => onChange({day: e.target.value, month: value.month})}
                       value={value.day}
                />
                <input type="text"
                       onChange={e => onChange({day: value.day, month: e.target.value})}
                       value={value.month}
                />
            </div>
        )
    }
}

DayAndMonthInput.defaultProps = {
    value: {day: 'xxx', month: 'yyy'}
}

Can the Form component use Field validation?

I couldn't find this in the documentation but if I am using the <Form> component can I also use <Field> validators or do I have to put all of the validations on the <Form>? Looking at the code it looks like it just pulls it off the <Form>.

[PROPOSAL] Higher-order reducer/reducer enhancer - "modellable()"

What does everybody think about providing a higher-order reducer (i.e. reducer enhancer) for creating a model reducer on top of an existing reducer? Code would look something like this:

import { modellable } from 'react-redux-form';

// existing user reducer
import userReducer from './user-reducer';

// modellable: (reducer, model) => reducer'
export default modellable(userReducer, 'user');

This would create a reducer that:

  1. Updates the state if the action is a RRF action (such as actions.change or actions.reset)
  2. Pass the updated state to the original reducer, as well as the action

This can also simplify the updating of stores in existing projects to retrofit the model reducers:

+ import { modellable } from 'react-redux-form';

const store = createStore(combineReducers({
-  user: userReducer,
-  foo: fooReducer
+  user: modellable(userReducer, 'user'),
+  foo: modellable(fooReducer, 'foo')
}));

This would not replace the existing createModelReducer(), which is quite useful when making new reducers.

In case "modellable" is too awkward to spell (or, as it might turn out, probably not even a word), we can call the enhancer:

  • modeled()
  • asModel()
  • modelEnhancer()
  • model()

Just some ideas. Thoughts?

Validation firing on load

I am validating using

<Form model="mymodel" validators={validators} validateOn="change">

  1. I am finding the validation is firing before any change as soon as the page loads.

I've adapted this fiddle as an example https://jsfiddle.net/wbd86ewj/

  1. Also to reset, I am finding I need to reset each field individually, so I am needing
dispatch(actions.resetValidity("mymodel.field1"))
dispatch(actions.resetValidity("mymodel.field2"))
dispatch(actions.resetValidity("mymodel.field3"))

instead of

dispatch(actions.resetValidity("mymodel"))

Which I saw mentioned

Update wiki typo

I can't send a PR for a wiki change, but I believe that this line is typo'd in the Redux-Form-Comparison page:

loginForm: createModelReducer('loginForm')

and should be

loginForm: createFormReducer('loginForm')

Problem with custom Field component in production build

I made my own field-wrapper wrote for react-bootstrap following "Custom Component Recipe"

import { createFieldClass, controls } from 'react-redux-form';

export const TextField = createFieldClass({
    'Input': props => ({
        onChange: (event, val) => props.onChange(event.target.value),
        value: props.modelValue
    })
});

export const CheckboxField = createFieldClass({
    'Input': props => ({
        onChange: (event, val) => props.onChange(event.target.value),
        checked: !!props.modelValue
    })
});

While development everything seems to be ok, but in production form doesnt work properly. Problem here is that in production UglifyJs change component name to shortcuts like "k" or "t"(if DisplayName not specefied)

One way to solve this is specify displayName, or make new prop that specify it.

I use that workaround right now

import { Input } from 'react-bootstrap';

Input.displayName = 'Input';

error validators for validateErrors action passes undefined parameter

Having an issue with the new actions.validateErrors(). Any time errorValidators are used, the parameter is logged as undefined, when it should reflect the current value of the user model reducer. For instance:

// somewhere with dispatch()
dispatch(actions.validateErrors('user.email', (val) => {
  console.log(val) // undefined
}))
dispatch(actions.validateErrors('user.email', {
  required: (val) => { console.log(val) } // undefined
}))

Documentation for Form component

Hi,

I found the field-components. However there are no docs and the component seems to define some none-self-explanatory properties.

Using it like this

import {Form} from 'react-redux-form';

...

render() {
  return <Form model="myReducer.myModel">
        { /* a lot of nested components here */}
  </Form>
}

yields this error:

Uncaught TypeError: Cannot read property 'props' of undefined`(form-component.js:49)

It seems that the this scope is not set correctly.

Action to reset form validation

I'm working with scenario where all validation is processed on server while attempting to post the form and get back list of errors. Now all works pretty nicely, except that on second submit I don't know what fields were fixed since the last update, so I can't clear their validation state, so my question is:

  1. is there a way to clear validation for all fields within given form state?
  2. is there a way to enumerate fields?

My action looks like this:

function create_control_submit(data) {
    return function (dispatch) {

        let request = new HttpRequest("/admin/users/api/create", "POST");

        return request.getResponse({ data: data })
            .then((response) => response.bodyAsJson())
            .then((response) => {

                if (response.validation) {

                    for (let state of response.validation) {
                        console.log("state", state);

                        dispatch(form.setErrors('createControl.createForm.data.' + state.name, state.error));
                    }

                }

            });
    }
}

Do we support dependent fields?

Hi, Thank you, this is very useful library.

I have a question that is there any example about dependent fields, let's say I have country and cities dropdown field, the cities field depends on the country's. How can we handle that case?

If we don't have it now but you plan to have it, let me know, I really want to help.

Immutable support doesn't seem to work

If I do

import { createModelReducer } from 'react-redux-form/immutable';

It doesn't work, even though that's the way it's supposed to work according to the docs. Any idea of what's wrong? Trying to import from react-redux-form/src/immutable also doesn't work.

How to prepopulate a form?

I'm probably missing something from the docs, but how do I prepopulate a form? Say I have a dialog that pops up with a form in it, and I have a few fields I'm passing as props to the form, and but I also want rrf in Redux to also be aware of the default values.

Form onSubmit always has undefined as argument

I'm not sure what I'm doing wrong, but I've got this:

      <Form
        style={styles.form}
        noValidate
        onSubmit={(adminOrg) => console.info(adminOrg)}
      >

And the console always dumps out undefined when I submit the form. How exactly does Form's onSubmit work? Where does it get its expected value from?

Fields do not update when underlying model updates

Hi! We're building a form-heavy Salesforce app and are running into a pretty major issue with react-redux-forms:

When you update an underlying form model, the field does not appear to be synced with the model. You can see this demonstrated in this fiddle:

https://jsfiddle.net/7t46vv0g/

Clicking the button does reset the underlying model, but does not reset the form field values.

Our expectation would be that clearing the model would also update the form fields, or failing that, that there be some other method of telling the form fields to sync with their models. It's hard to tell whether this is a bug or intended behavior.

Is there any way currently to do what we're looking for, without having to manually connect each input element to state?

Permit element to update sibling element

I have a select (months) that needs to update a sibling select (days in that month). However, I cannot get the onchange event attached to my months selector to update its sibling. I can output the updated info via console.log and it is correct, however the days select never updates from its initial state.

This exists as a SO question which has more detailed code if helpful.

Is this something that I should be having trouble with or perhaps is not a capability of this package (or maybe I have something misconfigured)?

FormReducer touched and untouched property don't reflect aggregated touched properties of children Fields

The result of createFormReducer has properties like touched, valid, pristine etc.

Some of these properties need to change based on Fields within that Form. For instance, if I touch the email field below, then newUserForm.touched should be true, yet it stays false.

<form className="ui-form -middle">

  <Field className="ui-field " model="newUser.email" validators={{
    valid: validator.isEmail,
    required : (v) => !!v
  }}>
    <label className="ui-label">Email</label>
    <input type="text" className="ui-input" />
    {!getField(newUserForm, 'email').valid && getField(newUserForm, 'email').touched && (
      <div className="ui-error">
        Please check your email address
      </div>
    )}
  </Field>

  <button type="button" className="ui-button"
    disabled={ !newUserForm.valid }
    onClick={(e) => dispatch(saveUser(newUser))}>
    Submit
  </button>

</form>

I want the submit button to be enabled under the condition that the form is touched and the fields are valid. So it would be disabled if the form isn't touched or one or more of the fields are invalid.

So, if I changed the submit button disabled attribute to:

{ !newUserForm.valid || !newUserForm.touched }

The disabled property would be wrong because .touched and .untouched don't update. They need to change if any one field within the form changed.

Semantically the reason is this: "If I touch a field within the form, I have touched the form."

rsf/change is updating two different models

I have two very similar reducers that are made up of nested reducers, like so:

// login.js
export default combineReducers({
    model: createModelReducer('auth.login.model', {
        email: '',
        password: ''
    }),
    form: createFormReducer('auth.login.model')
});
// registration.js
export default combineReducers({
    model: createModelReducer('auth.registration.model', {
        email: '',
        password: ''
    }),
    form: createFormReducer('auth.registration.model')
});

So the final state tree looks like:

    auth:
        login: {
            form,
            model
        },
        registration: {
            form,
            model
        }
    }

I have ensured that the model props on the <Field/> components are correctly set to auth.registration.model.email and auth.login.model.email respectively. However, when I start entering text into one of the inputs, the email field on both of these model reducers are responding to rsf/change actions, and they are both being updated with the same text, even though the payload of the change action only references one of the models. Any ideas?

Thanks for your work on this awesome package!

model reducer documentation

Hi! I am still learning about react-redux-form, but I thought I would let you know about a couple areas in the documentation that caused me a bit of confusion or that could possibly be improved.

One is that you discuss custom model reducers in the "Model Reducers" section and then again in "Using Existing Reducers". I think it would be clearer to consolidate discussion into one place.

The other is that using a reducer to store full name seems like an anti-pattern; it is just the sort of derived data that the React docs tell us we should recompute instead of storing in component state, and the same applies to Redux. It could be acceptable to store derived data in Redux if the computation were really expensive, but even then, unless I am misunderstanding something, I don't think you would have anything like the GET_FULL_NAME action; you would just have actions to set the underived data and a derived data reducer that would respond to those actions, no?

Thoughts on making a Field like higher order function instead of parent component?

I was really excited to discover your new module last night. I like the approach but found myself a bit confused over the Field component. It's obviously optional but I find myself longing for a higher order component I could pass a component to as an argument and have the event handlers and state slice applied as props to it. That way I can be sure to link to them up to the correct places within the custom component I send to it. Any reasons you decided against it in favor of the current <Field> approach? Thanks for your all your work thus far.

best way to validate multiple fields

What is the best way to validate multiple fields at once, for instance checking two password fields match, or at least one checkbox is ticked?

Issues with Field / createFieldClass and uglify2 mangling

Not sure how to give much more information than this: when using uglify2 with name mangling on (which is the default behavior) - the wrapper components that get created using Field or createFieldClass are not getting props passed through to the underlying component (so onChange never fires for instance - whether I am re-mapping onChange or not.)

It might also be caused by babel (I'm using 5.8) - honestly at this point in time, I have no idea how to efficiently debug stuff like this with multiple levels of transpiling and parsing and react magic.

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.