3

I'm using Redux Forms:

In Parent:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount() {
    console.log(this.myRef);
  }
  render() {
    return (
        <div>   
            <CustomField ref={this.ref} />
        </div>
    )
  }

In CustomField:

import { Field } from 'redux-form';
import Child from 'components/Child';
const CustomField = props => {
  return <Field {...props} component={Child} type="text" />;
};

I need to manage focus on the Child component from Parent. Normally you would use a forward ref but I'm not sure if this is possible with Redux Forms? The following is erroring and all the props are undefined:

const CustomField = React.forwardRef((props, ref) => {
  return <Field {...props} component={() => <Child {...props} ref={ref} />} type="text" />;
});

Message from the console:

Warning: Failed prop type: Invalid prop component supplied to Field.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
Evanss
  • 23,390
  • 94
  • 282
  • 505

1 Answers1

1

I got it working using the older syntax where you pass the ref as a normal prop. I think you have to call it something other than ref:

In Parent:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount() {
    console.log(this.myRef);
  }
  render() {
    return (
        <div>   
            <CustomField customRef={this.ref} />
        </div>
    )
  }

In CustomField:

import { Field } from 'redux-form';
import Child from 'components/Child';
const CustomField = props => {
  return <Field {...props} component={Child} type="text" />;
};

In Child (not sure if this needs to be a class or not):

class Child Extends React.Component {
  render(){
    return(
      <input ref={customRef}  />
    )
  }
}

The older style seems simpler to work with to me. As a tangential point it would be interesting if anyone could explain the downsides to it, as I assume there are some?

Evanss
  • 23,390
  • 94
  • 282
  • 505