Search code examples
reactjsmaterial-uiredux-form

Material-UI and Redux-form not styling when being mapped


I've created this codesandbox - https://codesandbox.io/s/pk8p4lvl90

I can implement the material-ui instructions (https://redux-form.com/7.2.2/examples/material-ui/) fine without the mapping mechanism, but as soon as I apply the mapping I can't get the material-ui to implement the look for a textfield.

In my example I have commented out the code I have tried that works without mapping being involved.

Form -

<form onSubmit={handleSubmit}>
  <div>
    {/* <Field
      name="firstName"
      component={renderTextField}
      label="First Name"
    />*/}
    <FieldArray
      name="firstName"
      component={renderTextField}
      label="First Name"
    />
  </div>
</form>

TextField Render -

    const renderTextField = ({ fields, input, label }) => (
      <div>
        {fields.map((newIntel, index) => (
          {/* <TextField 
                name={newIntel} 
                key={index} 
                label={label} 
                placeholder={label} 
                component="input" 
                placeholder={label} 
                label={label} /> */}

          <Field
            name={newIntel}
            key={index}
            label={label}
            placeholder={label}
            component="input"
            placeholder={label}
            label={label}
          />
        ))}

        <div
          variant="fab"
          color="primary"
          className="jr-fab-btn"
          aria-label="add"
          onClick={() => fields.push()}
        >
          Click me
        </div>
      </div>
    );

Solution

  • In order to use redux-form features with material-ui look, you need use redux-form's input component with render function that will return material-ui's component with appropriate props. You started doing so, but renderTextField should look a little bit differently, e.g.:

    const renderTextField = ({
      input,
      label,
      meta: { touched, error },
      ...custom
    }) => (
        <TextField
          hintText={label}
          floatingLabelText={label}
          errorText={touched && error}
          {...input}
          {...custom}
        />
      )
    

    Having this, you can reuse it in, let's say renderForm function:

    const renderForm = ({ fields, input, label }) => (
      <div>
        {fields.map((newIntel, index) => (
          <Field
            ...
            component={renderTextField}
            ...
          />
        ))}
        ...
      </div>
    );
    

    That's based on what I've found in the redux-form Docs you linked. Take another look there as well, it's well described there as well.