reactjsreduxfocusredux-formrefs

Focus on next Input field on Enter in Redux Form


I want to define a HOC(higher order Component) which will be responsible for handling the functionality. import React, { Component } from 'react';

const NextFieldOnEnter = WrappedContainer =>
  class extends Component {
    componentDidMount() {
      console.log('hoc', this.refs);
      //move to next input field
    }
    render() {
      return <WrappedContainer {...this.props} />;
    }
  };
export default NextFieldOnEnter;

It says this.refs is deprecated. So how can I achieve tab like behavior when enter key is pressed. My form is

<Form>
<Field
  withRef
  hasFeedback
  name="name"
  ref={ref => {
    this.field1 = ref;
  }}
  refField = "field1"
  component={makeField}
  type="date"
/>  
<Field
    withRef
    hasFeedback
    name="address"
    ref={ref => {
      this.field2 = ref;
    }}
     refField ="field2"
    component={makeField}
    type="date"
  />
</Form>

//makefield

render() {
  const {type, input, label, ref, refField, ...rest} = this.props;
  return (
    <Form.Item
      label={label}
      colon={false}
      type={type}
      value={value}
      ref={ref}
    >
      <Input {...props} />
    </Form.Item>
  );
}

Solution

  • In your constructor method define your ref like this

    constructor(props) {
      super(props);
      this.field1 = React.createRef();
      this.field2 = React.createRef();
    }
    

    In your render where you are using ref do this.

    <Field
      withRef
      hasFeedback
      name="name"
      ref={this.field1} // Proper way to assign ref in react ver 16.4
      refField = "field1"
      component={makeField}
      type="date"
    />  
    

    Reference Refs Documentation React