HSBP
HSBP

Reputation: 765

How to autofocus redux field

I want to autofocus first redux field. I have tried many different options available but none of them worked. So whenever the form gets created, it should focus to first field.

           <Field
              name={'Email'}
              label="Email *"
              onFocusCb={this.hideDoneButton}
              component={FormInput}
              containerStyle={styles.inputStyle}
              clearButtonMode={'always'}
              autoCorrect={false}
          />

I have created the component{FormInput} outside the class. Below is the code for the same.

const FormInput = props =>
(<View style={props.containerStyle}>
<FormTextInput
    autoFocus={true}
    multiline
    style={props.style}
    autoCapitalize={props.autoCapitalize}
    clearButtonMode={props.clearButtonMode}
    selectionColor={props.selectionColor}
    value={props.input.value}
    onFocus={props.onFocusCb}
    keyboardType={props.keyboardType}
    label={props.label}
    placeholder={props.placeholder}
    defaultValue={props.defaultValue}
    onChangeText={text => props.input.onChange(text)}
    onEndEditing={() => {
      if (props.onEndEditing) {
        props.onEndEditing();
      }
      if (props.input.onEndEditing) {
        props.input.onEndEditing();
      }
    }}
/>
</View>);

Upvotes: 1

Views: 838

Answers (1)

jonahe
jonahe

Reputation: 5000

You could use the HTML5 attribute autoFocus. This solution is not related to Redux form.

<Field
          autoFocus
          name={'Email'}
          label="Email *"
          onFocusCb={this.hideDoneButton}
          component={FormInput}
          containerStyle={styles.inputStyle}
          clearButtonMode={'always'}
          autoCorrect={false}
      />

There are ways to do it within Redux-form, like setting the props ref, withRef, use getRenderedComponent() and then calling .focus(), but for this simple behavior it's not clear what the benefit, over just using autoFocus, would be.

Upvotes: 1

Related Questions