final-form / react-final-form Goto Github PK
View Code? Open in Web Editor NEW๐ High performance subscription-based form state management for React
Home Page: https://final-form.org/react
License: MIT License
๐ High performance subscription-based form state management for React
Home Page: https://final-form.org/react
License: MIT License
React react-final-form component collect config for final-form and there not exist property validateOnBlur
const config: Config = {
debug,
initialValues,
onSubmit,
validate
}
Any reasons to skip validateOnBlur
property?
If true
, validation will happen on blur. If false
, validation will happen on change. Defaults to false
.
I would suggest adding another config option;
validateOnChange: bool
validateOnBlur: bool
I'm considering abandoning my own attempt at a form library (it was a great learning experience though), since you certainly know more about the different pain points users have, and the internal workings of React and how to properly do performant libraries, considering your background with forms and React.
One thing I really liked with my solution was the ability to do sync validation onChange, and async (i.e network requests) on onBlur.
I haven't figured out another way to do this just yet. But If we can have the library to validate on both onChange and onBlur this would be possible.
Hi again.
Maybe you have any thoughts how to make scrolling to first error message using your validation library?
Feature Request
Hey @erikras, congrats on a new shinier form library ๐ I wanted to bring back an old feature request on Redux-Form to see how to achieve that with RFF
redux-form/redux-form#2169 (comment)
Essentially, the usecase is to be able to save form fields onChange
/onBlur
and submit only that form field back to the backend. This is super useful for really long forms and often a better UX.
What do you think would be the way to be able to do that with RFF?
Thanks!
Hi Erik,
Excellent library, simply fantastic work here!
Can you share a best practice for implementing a normalizer function? I'm looking for similar functionality to the normalize prop available to the Field component in redux-form. I'm able to achieve normalizing through the addition of conditions to an inputs onChange function. Would this be the recommended approach?
Probably a bug
Field has name
prop both in input
and meta
props.
From the docs, meta
should not have duplicate name
prop, it exists only in input
props.
https://codesandbox.io/s/5z7z467o4l
Open the console and you'll see it.
Hi,
I want create a form with react-google-maps and react-final-form.
When the onDragEnd event of map is fired, I want update the latitude input and longitude input of my form.
The user can also edit the map by changing the values in the inputs.
I can't use the props value
in the Field component...
How can I do it?
Forms:
class AddressForm extends PureComponent {
constructor(props) {
super(props);
this.state = {
coords: {},
};
this.onChangeCoords = this.onChangeCoords.bind(this);
}
onChangeCoords({ lat, lng }) {
this.setState({
coords: GeoPoint(lat, lng),
});
}
render() {
const { onSubmit, data } = this.props;
const { coords: { latitude, longitude } } = this.state;
const initialValues = {
...data,
lat: data.coords.latitude,
lng: data.coords.longitude,
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
render={({ handleSubmit, pristine, invalid }) => (
<form className="all-forms" onSubmit={handleSubmit}>
<div className="map">
<Maps
coords={{
lat: latitude || data.coords.latitude,
lng: longitude || data.coords.longitude,
}}
onChangeCoords={this.onChangeCoords}
/>
<Input name="lat" label="Latitudine" type="text" validate={string} />
<Input
name="lng"
label="Longitudine"
type="text"
validate={string}
/>
</div>
<Button type="submit" disabled={pristine || invalid} label="Salva" />
</form>
)}
/>
);
}
}
INPUT:
class Input extends PureComponent {
render() {
const {
name, label, type, validate,
} = this.props;
return (
<label htmlFor={name}>
{label}
<Field name={name} validate={validate}>
{({ input, meta }) => (
<div>
<input {...input} className="text-field-default w-input" type={type} />
</div>
)}
</Field>
</label>
);
}
}
I want user from multi select drop down or checkbox's select some fields, And based on those fields, show other textfields corresponding to selection.
how do i do something like this ?
Feature request: I would like to be able to subscribe to form updates for the purpose of autosave without submission. I am currently using FormSpy
to do this but its render function is also triggered by parents rerendering:
<FormSpy subscription={{ values: true }}>
{({ values }) => {
onChange(values);
return null;
}}
</FormSpy>
It would nice if there was easy way to listen to updates without it also trigging on renders and gives the granularity subscriptions offer (debug
is too noisy). I could get hold of reactFinalForm
from context
but this in not part of the public API.
One of the following would work for me:
onChange
prop on FormSpy
subcription
and onChange
as props
reactFinalForm
from the context
reactFinalForm
being exposed as a render prop on FormAm I missing something, is there already a way to do this?
I confused because I didn't find any general purpose state management library mention.
As I understand its Observer pattern does not compatible with redux. What with mobx?
Is final-form vertically integrated and cannot work with usual state management lib?
Feature request
Submitting a form with no event results in a runtime error.
I'm using React Final Form on React Native and I don't always have an event passed to the submit handler.
<Form
onSubmit={this.onSubmit}
initialValues={/* ... */}
render={({handleSubmit, reset, submitting, pristine, values}) => (
<View style={styles.container}>
<NavigationBar
leftButton="back"
onLeftButtonPress={this.props.navigator.pop}
rightButtonText={t("Save")}
onRightButtonPress={handleSubmit}
/>
...
</Form>
Obviously bad example just to show the error: https://codesandbox.io/s/k10xq99zmr
React Native 0.48
Final Form 3.0.0
React Final Form 2.1.0
It's easy to bypass this error with this:
onRightButtonPress={() => {
handleSubmit({preventDefault: () => {}});
}}
But I would rather have a check in the handleSubmit
function to bypass the preventDefault
call if no event is passed.
following up on #25
Would be great to have an example, like the field arrays to add/remove objects along with array.
Hello! Is there any possibility to pass initial values after form created. Or change particular value from upper component.
I prefill my form using query after form is rendered and I can not pass loaded values to inputs.
Thanks
Provide a set of callbacks to onSubmit method, for example reset
function
feature request
<Form
onSubmit={onSubmit}
initialValues={{ employed: true }}
render={({ handleSubmit, reset }) => (
<form
onSubmit={event => {
handleSubmit(event).then(() => {
reset() // or could be passed directly to then()
})
}}
>
...
</form>
}/>
const onSubmit = (values, reset) => {
return new Promise (resolve => {
reset();
resolve();
}
};
<Form
onSubmit={onSubmit}
initialValues={{ employed: true }}
render={({ handleSubmit, reset }) => (
<form onSubmit={handleSubmit}>
...
</form>
}/>
This works perfectly on any other call I've made, but once I use it in React-Final-Form's onSubmit, it no longer works. What could be the issue?
<RFForm
onSubmit={(values, cb) => {
const formData = new FormData();
formData.append('files', values.files);
formData.append('values', values);
axios.post('/api/forms/test', formData, {
headers: {
'content-type': 'multipart/form-data'
}
})
.then(response => cb())
.catch(error => cb({ error }));
}}
validate={validate}
component={ExpenseForm}
/>
It's a bug although I'm not sure if it's caused by react-final-form
.
In some specific cases, checkbox does not fire onChange
handler function on the first click. This will work fine:
const Input = props => <input {...props} />;
const Checkbox = ({ children, ...restProps }) => (
<label>
<Input type="checkbox" {...restProps} />
{children}
</label>
);
// then inside a Form
<Field
name="good"
render={({ input }) => (
<Checkbox {...input}>It works as expected</Checkbox>
)}
type="checkbox"
/>
This will cause a bug:
const Checkbox = ({ children, ...restProps }) => {
const Input = props => <input {...props} />;
return (
<label>
<Input type="checkbox" {...restProps} />
{children}
</label>
);
);
// then inside a Form
<Field
name="bad"
render={({ input }) => (
<Checkbox {...input}>
It is <b>not working on first click</b>.
</Checkbox>
)}
type="checkbox"
/>
onChange
handler should be fired.
https://codesandbox.io/s/k5y0znj02v
package | version |
---|---|
React Final Form | 1.1.1 |
Final Form | 1.2.1 |
OS | macOS Sierra (10.12.6) |
browser | Chrome 62 (note: the bug doesn't appear in Firefox nor Safari) |
Hey, #3 is still an issue.
I've updated the codesandbox demo to 1.1.0 and I can get all errors
from the form, but I can still submit it.
Validation errors check should probably be added in hasSyncErrors
here, but how's this test passing then.
Am I missing something? ๐ค
Hey there ๐ . What do you recommend for the validation library?
Formik recommends yup, just curious what final-form does recommend.
Keep up the good work โค๏ธ
How do I set a prop that is specific to a third-party library and does not catch an error?
For exmaple
<Field
name="firstName"
component={SomeComponentFromThirdParty}
validate={required}
somePropByThirdParty="AnyValue"
/>
I get type error
TS2339: Property 'somePropByThirdParty' does not exist on type
feature request
add onChange FormProps (similar to RRF)
Hello. How I can submit form from outside sibling component? Example I want submit form by button from modal window
The value lifecycle is one of the best features from redux-form. Will react-final-form support something like that?
bug
Form does not filled using initialize method.
Fill form after form is created.
https://codesandbox.io/s/xo33o77j7q
pls, see sandbox
i posted a question for you in tracker, but it was ignored so i tried myself and this is what i got
Bug report
Upgraded Material ui to 1.0 Beta and sing material UI button element, Does not call the function onClick.
How do I make final form with 3rd party component like Material UI ?
on Button click it should show the form json
https://codesandbox.io/s/wn5v2q3lj7
Material ui 1.0 beta
Feature request
Type errors with react-native + typescript
No type errors :P
I'm using react-final-form with react-native
"react-final-form": "^2.1.1",
"final-form": "^3.0.0",
"react": "16.0.0",
"react-native": "0.50.4",
There are two situations where I have type errors.
The current type for handleSubmit is:
handleSubmit: (event: React.SyntheticEvent<HTMLFormElement>) => void
How can we deal with this in react-native?
onPress events of touchables have this signature:
onPress?: (event: GestureResponderEvent) => void;
Sometimes we need to pass some extra props to the underlying component of Field
<Field
name='firstName'
component={TextInputField}
style={styles.textInputStyle}
/>
In this case, the style
prop is the extra one.
The type system complains because the props that Field is expecting are:
export type FieldProps = {
allowNull?: boolean
format?: ((value: any, name: string) => any) | null
parse?: ((value: any, name: string) => any) | null
name: string
subscription?: FieldSubscription
validate?: (value: any, allValues: object) => any
value?: any
} & RenderableProps<FieldRenderProps>
Maybe we should allow anything here? :\ ๐
I want a fields values to be integer. But when I try TextField from material ui, with type="number"
The value in form still is a string. Any thoughts if only string can be saved as values in form or int/json etc can also be saved ?
Hey :)
Bug report
Even with validation errors, I am able to submit a non-valid form if not all fields are rendered.
I expect that I will be not able to submit a non-valid form that has validation errors.
I took Synchronous Record-Level Validation example and slightly modified it - removed two fields and added console.log
with validation errors.
Here is a codesandbox demo - https://codesandbox.io/s/53xrn6v86p
Try to submit an empty form and you will have 3 validation errors. Now, fill in the only field in the form and you'll still have 2 validation errors. Even though you have errors left, you will be able to submit the form.
This bug also exists in redux-form and was mentioned in issues multiple times. ๐ข
Maybe it'll be fixed in the final-form
(the title sounds awesome) ๐
It would be great to be able to use final-form and react-final-form from TypeScript fully typed. Hopefully this would be fairly easy, as you already have Flow types. I'm not aware of any automated conversion, though.
If I want my final forms object on submit to look like this how would I do it ?
{
name : 'kk'
address: {
street: '123 abc',
city: 'sf'
}
}
I know something like this is in works and will be there in future: https://redux-form.com/7.1.2/examples/fieldarrays/
but wondering if something like what I want is possible now ?
Currently migrating from redux-form;
Are there intentions to support immutable data structure a la redux-form/immutable ?
Thank you!
Hi there !
I was wondering how i can reset my form on successful submit ?
Seems that we don't have access to the reset()
function in onSubmit()
.
How can i handle that ?
Thanks for the work by the way , react-final-form is awesome :)
The following branches are all merged into master
, so I guess they can be deleted?
Just keeping the repo a bit cleaner ๐
validateFields
in type definition for FieldPropsWhen I try to compile a Field using validateFields={[]}
the TypeScript compiler gives me an error:
error TS2339: Property 'validateFields' does not exist on type 'IntrinsicAttributes & { allowNull?: boolean | undefined; format?: ((value: any, name: string) => ...'.
My sample code is:
<Field name="last_name" validate={this.validateRequired} validateFields={[]}>
{( { meta, input } ) => (
<input
type="text"
className={(!meta.pristine || meta.touched ? meta.error || 'Valid' : '' ) as string}
{...input}
/>)}
</Field>
I changed the FieldProps definition in index.d.ts
and the error went away:
export type FieldProps = {
allowNull?: boolean
format?: ((value: any, name: string) => any) | null
parse?: ((value: any, name: string) => any) | null
name: string
subscription?: FieldSubscription
validate?: (value: any, allValues: object) => any
value?: any
validateFields?: string[]
} & RenderableProps<FieldRenderProps>
Can you confirm? I can submit a PR with the change if ok with you.
Thank you
Michele
Maybe a bug or just a example with radio button and pristine and value.
I want a example with a checked radiobutton because, I want submit my form only if a data change but when I try it in the simple example I added checked="true" on the Field. I don't have the value curly properties (in JSON.stringify(values, 0, 2) in the value but a empty object.
You can look at:
https://codesandbox.io/s/71p6o782j6
Thanks
bug report and documentation improvement request
I have a component that uses render prop.
Let's take an example:
const CustomSelect = ({ input, meta, render, children, ...restProps }) => (
<select {...input} {...restProps}>{render && render()}</select>
);
I want to be able to use it with Field
component like that:
const countries = [
<option key="placeholder" value="placeholder" disabled>
Select your country
</option>,
<option key="de" value="de">
Germany
</option>
];
<Field
name="country"
component={CustomSelect}
render={() => countries}
/>
With current Field
implementation, render prop will not be passed down to my CustomSelect
component. However children
prop would be passed. Consequently, we're not able to use form components that use render prop (this is such an awesome pattern, isn't it?).
The other problem is that this is inconsistent behavior because both render
and children
props are part of Field
API. One of them is being passed down, the other is not.
Both children
and render
props should be passed down if component
is used.
Also, the documentation should explain an order in which component
, render
, and children
are used for rendering as well as what happens when you use more than one of them at the same time.
package | version |
---|---|
React Final Form | 1.1.1 |
Final Form | 1.2.1 |
input.onChange() and input.onBlur() by themselves do not make a field touched. You MUST call input.onFocus() as well as onBlur to actually make the field touched.
export const CustomerSearch = (({ input, meta, label, ...rest }) => {
return (
<Form.Field>
<label>{label}</label>
<Search
{...input}
{...rest}
list={[
{ title: 'thing 1', description: 'desc 1' },
{ title: 'thing 2', description: 'desc 2' },
]}
onChange={result => input.onChange(result)} // this works
onBlur={() => input.onBlur()} // this will not mark field as touched
/>
<div className="field-error-text">{meta.touched && meta.error}</div>
</Form.Field>
);
})
You have to call onFocus if you are going to call onBlur. This will make it work. onBlur by itself should make the field touched in my opinion
example request
Feature request
I might missing something, but what is the correct approach to reset a form after successful submission? Without having a reset button of course.
I couldn't see anything about this in the documentation.
I can inject new empty initialValues
from props maybe, but it doesn't seem very clean.
I interpret it as a bug, because it is not the expected behavior, so bug report!
The validation message that is used on the validate
method is instantiated once and that is the static message used for the rest of the renders. With static text this is fine, but when using internationalization libraries like i18next that can have bundles dynamically loaded, this can cause issues because the non-internationalized string key is shown instead of the internationalized value.
const isFoo = (value) => {
return value === 'foo';
};
const getErrorMessage = (t, i18nKey) => {
return (isValid) => {
return isValid ? undefined : t(i18nKey);
};
};
// in component
validate={compose(getErrorMessage(t, 'some.key'), isFoo)}
The i18next
thing is just one example, but any sort of dynamically-built message will not be dynamically built!
That when items are invalid the current message is used.
Final Form version => 1.0.0
OS => Manjaro Linux
Node version => 8.9.1
I report a bug
I initialized a value, when I change the value and I come back on the initial value of the select component, the pristine doesn't work.
The values are the same.
I Fork the Third Party Components example here:
https://codesandbox.io/s/yw6y5y00yx
Thanks @erikras
A bug or a very unfortunate feature
When a form is loaded, validation is triggered multiple times.
When a form is loaded, validation is triggered once.
https://codesandbox.io/s/v5ywx6nxl
There are 3 fields in the demo, from console log you can see that validation was triggered 4 times.
Cannot read property 'then' of undefined
FormComponent.js
const { handleSubmit, reset, values, pristine, invalid, submitting, submitFailed, submitSucceeded } = props;
return (
<form onSubmit={event => {
const promise = handleSubmit(event);
console.log('heyyy :-D', promise);
promise.then(() => {
reset();
})
return promise;
}}>
FormContainer.js
<Form
onSubmit={(values) => {
return new Promise(resolve => {
axios.post('/api/forms/creditdebit', { values, options })
.then(response => resolve())
.catch(error => resolve({ error }));
});
}}
component={FormComponent}
/>
Hi!
possibly bug
Please use sandbox.
steps to reproduce:
i think its better to hide backend message when user start editing field
Using example from : https://material-ui-next.com/demos/text-fields/#textfield for dropdown.
I am unable to use it with forms. Please can we update our example of 3rd party component integration to use material ui v1 beta ?
@erikras Thanks for help
In redux form there is a Wizard form example, But I want to do something similar where when user selects from a dropdown an option, I want to render different form elements for user to input.
Maybe this is not right way of thinking: But the way im thinking now is , I create various different forms and then on dropdown or click, I render different form to user to input data.
And end of nested form/wizard, if I can have 1 JSON or final values to submit, which is aggregate of all different form values user submitted.
Wondering how to structure large forms using react-final-form,
Does it all just go in 1 javascript file of all fields or are there examples on how to split up sections of forms in separate components all using same form ? Wizard form looks close enough, but not sure if thats how it should be for non-wizard forms ?
One of the things that I love about redux-form
compared to formik
is that redux-form
supports complex form data such as arrays of objects. Are there any plans to include similar functionality here?
Not sure if this is expected behaviour.
But when you set the "validate" prop of a Field, the component also gets the "validate" prop passed to it. Usually api props shouldn't get passed down to inner components.
It's pretty trivial to work around though.
Hi, thank you for your effort on this new promising library. I've made some tests if it's suitable for my project and found only this issue:
A bug report.
When I'm using asynchronous field-level validation everything works fine except on Form unmounting (the form is successfully submitted and the page is changed via react router) an error will rise:
final-form.es.js:561 Uncaught (in promise) TypeError: Cannot set property 'error' of undefined
at final-form.es.js:561
at Array.forEach (<anonymous>)
at processErrors (final-form.es.js:557)
at final-form.es.js:581
at <anonymous>
When I look into the final-form.es.js:561
and add a check if fields[name]
is not undefined
everything works fine.
Last form values before the error rises is according to the debug={console.log}
an empty object {}
.
I was not able to reproduce it on any simplified example yet.
RFF 1.2.0, FF 1.3.0
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.