Redux Form v6 - Generating a dynamic form with unique keys loses focus on value input
hope someone knows the problem. I have an array like:
let fields = [
{ name: 'email', type: 'email', placeholder: 'Email', component: FeedbackInput },
{ name: 'password', type: 'password', placeholder: 'Passwort', component: FeedbackInput }
];
And I want to render it in my redux form via:
<form onSubmit={ handleSubmit(this.props.startAnimation.bind(this, 'animatedBtnConfig')) }>
<fieldset>
{ fields.map(field => <Field key={_.uniqueId('field_')} { ...field } component={ FeedbackInput } />) }
</fieldset>
<fieldset className="center">
<AnimatedButtonRedux />
</fieldset>
</form>
So the problem is the form is original and I can only enter 1 character. Then it loses focus from the input field and clicks on it again.
Same problem when I try to use it using the "FieldArray":
<FieldArray name="authData" component={ DynamicFields } fields={ fields } />
Dynamic fields component:
export default props => {
console.log("Dynamic Fields: ", props);
return (
<div>
{ props.fields.map(field => <Field key={_.uniqueId('field_')} { ...field } />) }
</div>
);
};
Instead, when I try this:
<Field { ...fields[0] } />
<Field { ...fields[1] } />
<Field { ...fields[2] } />
Works well.
I don't see any difference in devtool when I look at the DOM. Why does the redux form behave like this? I can not understand. I would really appreciate it if someone could give me a resolving question to resolve this issue!
source to share
This is due to unique id
what you provide as a key
component Field
likekey={_.uniqueId('field_')}
So what happens when your component is reloaded, edit the checks for key
DOM rendering, because yours is key
generated uniquely every time the component is rendered and the function is map
run, your Field
component is replaced with a new one every time, and hence you see this problem.
Although you need to set a key and it must be unique in the document, it must remain the same on every render.
So change the key to
<fieldset>
{ fields.map((field, index) => <Field key={index} { ...field } component={ FeedbackInput } />) }
</fieldset>
source to share