Search code examples
reactjsmobiscroll

How to get the ref from a Mobiscroll child component into the parent


I'm trying to get a Child's state into the parent. After moving the Child's state and method into the parent, I've got the following:

export default class Parent extends React.Component {
  constructor() {
    super();
    this.state = { mpc_steps: { price: 0, credits: 0, text: "MPC Credits" } }
  }

  setMPCSteps = () => {
    let step = this.refs.mpc_slider.instance.getVal(); // Will fail
    this.setState({
      mpc_steps: { 
        price: step * 200, 
        credits: step, 
        text: "MPC Credits" 
      }
    });
  };

  render() {
    return(
      <div>
        <Child getCredits={this.setMPCSteps} getParentState={this.state.mpc_steps}/>
    )
  }
}

Child component:

export default class Child extends React.Component {
  render() {
    return (
      <Fragment>
        <mobiscroll.Slider
          ref="mpc_slider"
          value={this.props.getParentState}
          onChange={this.props.getCredits}
        >
          Buy Credits @ $2/Credit
        </mobiscroll.Slider>
      </Fragment>
    )
  }
}

I need to somehow call the Child's ref value from the parent. The problem is that the mobiscroll ref isn't defined from the parent. Is there a simple way of doing this? Any hints are welcome.


Solution

  • You can use React.forwardRef api:

    Child component:

    class Child extends React.Component {
      render() {
        return (
          <Fragment>
            <mobiscroll.Slider
              ref={this.props.innerRef}
              value={this.props.getParentState}
              onChange={this.props.getCredits}
            >
              Buy Credits @ $2/Credit
            </mobiscroll.Slider>
          </Fragment>
        )
      }
    }
    
    export default React.forwardRef((props, ref) => <Child innerRef={ref} {...props}/>);

    And use it like:

    <Child ref="mpc_slider" />