Search code examples
reactjsredux-form

How to use Normalize in Redux - Form Fields component


I have a question about Redux Form

https://redux-form.com/7.0.4/examples/normalizing/ - this one

I combined two inputs with Fields component, and in each of this input i wanna use Normalize method from Redux-Form, how i can do that?

Example:

<Fields 
  names={[ 'first', 'last' ]} 
  component={this.renderFields}
/>

const renderFields = (fields) => (
 <div>
  <input {...fields.first.input}>
  <input {...fields.first.input}>
 </div>
)

Solution

  • I think you'll have to manually run the normalize functions:

    const renderFields = (fields) => {
      const first = fields.first;
      const onChangeFirst = (event) => {
         const newValue = event.target.value;
         // normalize is passed down as a prop as well
         const normalizedValue = fields.normalize(newValue);
         // pass the normalized value to the Redux-Form onChange
         first.input.onChange(normalizedValue);
      };
    
      const last = fields.last;
      // do the equivalent thing for "last"
      // const onChangeLast  .... ...
    
      return (
         <div>
           <input {...first.input} onChange={ onChangeFirst }>
           <input {...last.input} onChange={ onChangeLast } >
         </div>
      );
    }
    

    Then you would use it like

    <Fields 
      names={ [ 'first', 'last' ] } 
      component={ this.renderFields }
      normalize={ myNormalizeFunction }
    />
    

    You can see a working JSFiddle demo here.