0

I have a data like this:

constructor(props) {
    this.a = React.createRef();
    this.b = React.createRef();
    this.c = React.createRef();
}

setValue = (data = {}) => {
    const {a='', b='', c=''} = data.constructor === ({}).constructor ? data : {};
    this.a.current.setValue(a, data => {
      this.b.current.setValue(data.b, data => {
         this.c.current.setValue(data.c);
}
}
}
}

How could I passing that to my customized Component like this:

<CusComponent ref={this.a}>

Here is the function to get value in CusComponent:

 value = function (a,b,c) {
    if (arguments.length) {
    if (a) {
      this.setState({a}, () => {
         this.value_a.value(a);
         if (b) {
           this.setState({b}, () => {
             this.value_b.value(b);
             if (c) {
               this.setState({c}, () => {
                 this.value_c.value(c);
    }
    }
    })

}
}
}

Thanks a lot!

1 Answers1

0

Yes you can pass a ref down to a child component with:

<CusComponent ref={this.a}>

Make sure you create CusComponent with React.forwardRef because that creates an argument ref alongside props. This `ref you can directly bind to anything in your child component.

const CusComponent = React.forwardRef((props, ref) => (
  <button ref={ref}>
    {props.children}
  </button>
));

You can read more in detail about this in the documentation.

If however both your parent and child component are class components then pass down the ref to CusComponent like so:

<CusComponent childref={this.a}>

Name the property something other than ref. Then you can access this ref in child component like below eg.

export default class CusComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <div ref={this.props.childref}>Here</div>;
  }
}
Amruta
  • 1,295
  • 1
  • 13
  • 24