Reputation: 2866
I have a feature that's built where I retrieve information from a database and populate them into redux form. However, what I'm stuck at is I want to save a "save changes" button appear whenever the user makes any changes to the forms so that this button can appear and overwrite their entry in the database.
For example: I have a button:
View Links
Now when any changes in the form happens, this changes to
Save Changes
How would I go about doing something like this? I was wondering if I could maybe attach a dispatch to the forms' onChange
so it can add a changed: true
state. Otherwise, is there a way that to achieve something like this with redux-form?
Upvotes: 0
Views: 1199
Reputation: 4126
Use these boolean Properties dirty
and pristine
that redux-form gives your decorated redux-form component.
Pristine is true when form values are unchanged and dirty is true when form values have been changed.
You can then use them and ReactJs if-conditions to show other components as you see fit.
Example;
import React from 'react';
import { Field, reduxForm } from 'redux-form';
const SimpleForm = props => {
const { handleSubmit, pristine, dirty, reset, submitting } = props;
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
/>
</div>
</div>
<div>
<label>Last Name</label>
<div>
<Field
name="lastName"
component="input"
type="text"
placeholder="Last Name"
/>
</div>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>Submit</button>
{dirty &&
<button type="button" disabled={pristine || submitting} onClick={reset}>
Save Changes
</button>
}
{pristine &&
<button type="button" disabled={submitting} onClick={reset}>
View List
</button>
}
</div>
</form>
);
};
export default reduxForm({
form: 'simple', // a unique identifier for this form
})(SimpleForm);
You can see I use {dirty && component_to_render}
to only render that component when the form has received any changes and using
<button type="button" disabled={pristine || submitting}> Submit </button>
to disable the button when nothing has been changed or while the form is submitting.
Above is a code sample (with minor edits) from basic redux-form example and my full edited code is available here
Upvotes: 1