Piotr Żak
Piotr Żak

Reputation: 2132

Redux Form -> Autofocus first input

I have component in Redux-Form, I need an autoFocus on

Now it's doesn't working. What should i do for everytime autofocus first input?

const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <div className ="group">
      <input className="text"
      {...input}
      type={type}/>
      <label>{label}</label>
      <span className="highlight"></span>
      <span className="bar"></span>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)


  <Field name="name"
    type="text"
    component={renderField}
    label="Username"
    autoFocus
    require/>

  <Field name="email"
   type="email"
    component={renderField}
     label="Email"
    require/>

Upvotes: 1

Views: 571

Answers (1)

Noitidart
Noitidart

Reputation: 37238

autoFocus does not get placed into the input group. We need to manually handle this.

The only keys that get into input are:

export type InputProps = {
  checked?: boolean,
  name: string,
  onBlur: { (eventOrValue: Event | any): void },
  onChange: { (eventOrValue: Event | any): void },
  onDrop: { (event: Event): void },
  onDragStart: { (event: Event): void },
  onFocus: { (event: Event): void },
  value: any
}

As seen in the source code - https://github.com/erikras/redux-form/blob/master/src/FieldProps.types.js.flow#L29-L38

Also seen in the docs - https://redux-form.com/7.3.0/docs/api/field.md/#input-props

So we would modify our renderField to handle all other props and pass it to the input like this:

const renderField = ({ input, label, meta: { touched, error, warning }, custom, ...inputProps }) => (
  <div>
    <div className ="group">
      <input className="text" {...input} {...inputProps} />
      <label>{label}</label>
      <span className="highlight"></span>
      <span className="bar"></span>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)

Notice the change, it is now <input className="text" {...input} {...inputProps} />.

I added custom to the destructure so that it gets removed as this is what is in FieldProps - https://github.com/erikras/redux-form/blob/master/src/FieldProps.types.js.flow#L40-L63

Upvotes: 1

Related Questions