Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply CSS to redux-form fields?

How do I apply any type of CSS to redux-form Field components? className and class are silently ignored:

        <div>
          <label>Name</label>
          <div>
            <Field
              className="form-input"
              name="formContactName"
              component="input"
              type="text"
              placeholder="Person to contact"
            />
          </div>
        </div>

I was able to the apply the styles by creating a custom component:

        <div>
          <label>Name</label>
          <div>
            <Field
              name="formContactName"
              component={ customInput }
            />
          </div>
        </div>

but that's a major PITA and also largely negates the gains of using redux-form in the first place. Am I missing something? Note I added the className assignments directly in the custom component - I realize I can send them through as props in Field.

I tried setting input styles globally but they were ignored as well. The redux-form website docs tell you everything you need to know to use the rig but make no mention of CSS that I can see...

Thanks,

JB

Edit: this is not a duplicate - the answer pointed to uses a custom input component. As stated above, I can get that to work, but then there's really no need for redux-form in the first place.

@Jay: I was able to get this to work with a custom component by grabbing the code from the online docs:

class MyCustomInput extends Component {
  render() {
    const { input: { value, onChange } } = this.props
    return (
      <div>
        <label htmlFor="formContactName" className="col-sm-2 control-label">Name:</label>
        <div className="col-sm-10">
          <input
            id="formContactName"
            placeholder="Person to contact"
            className="form-control"
            type="text"
          />
        </div>
      </div>
    )
  }
}

and then, in the redux-form Form code:

    <div>
      <label>Name</label>
      <div>
        <Field
          name="formContactName"
          component={ MyCustomInput }
        />
      </div>
    </div>

The bootstrap settings via className worked fine using this method.

like image 984
Omortis Avatar asked Dec 16 '17 18:12

Omortis


1 Answers

All your custom props would be passed to the input component, so you can do

const CustomTextField = props => {
  const { input, label, type, meta: { touched, error }, ...other } = props

  return (
    <TextField
      label={label}
      type={type}
      error={!!(touched && error)}
      helperText={touched && error}
      { ...input }
      { ...other }
    />
  )
}

And then you can pass any props, including className to the CustomTextField

<Field
  name="some"
  component={CustomTextField}
  className="css-applied"
/>
like image 80
Dmitriy Kovalenko Avatar answered Oct 24 '22 01:10

Dmitriy Kovalenko