Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Ref through React Router To the Components?

I Have a following Setup

<Overview>
    <div className={styles.container}>
      <HeaderComponent/>
      <SecondaryHeader section={this.state.section} ref = {myref}/> // this ref how do i pass it to all the child components which are in routes
    </div>
    <div>
        <Routes fullScreenCB = {this.goToFullScreen}/>
    </div>
    <NetworkCheck/>
  </div>
</Overview>


const Routes = ({fullScreenCB}: IRouteProps) : React.ReactElement<IRouteProps> => {
      <Route exact path="/" component={withAuth(Home)} />
      <Route exact path="/about" component={withAuth(About)} />
      <Route exact path="/topics" component={withAuth(Topics)} />

})


myProtected Route HOC



export default (ProtectedRoute, fullScreenCB) => {


  class WrapperClass extends React.Component<any, {}> {
    constructor(props) {
      super(props);
      this.state = {
        isAuthenticated: process.env.NODE_ENV === "development" ? true : false
      };
    }

    render() {
      if (this.state.isLoading) {
        return (
          <div style={{width: "100%", height: "100%"}}>
              <CircularProgress style={{left: "50%", marginTop: "30%"}} size={"xlarge"}/>
          </div>
        )
      } else if (this.state.isAuthenticated) {
        let {forwardedRef, ...rest } = this.props;
        rest = {...rest, fullScreenCB};
        return (
          <ProtectedRoute
            ref={forwardedRef}
            {...rest}
          />
        )
      }
    }
  }

  let WrappedComponent = React.forwardRef(
    function withAuthorizationWarpper(props, ref) {
      return <WrapperClass {...props} forwardedRef={ref}/>;
    }
  );

  hoistNonReactStatic(WrappedComponent, ProtectedRoute);

  return WrappedComponent;
}

How do i pass the Ref of the Secondary Header to the Child Routes i tried forwarding Routes but to no avail. I am a bit confused in the concept. I know how to pass it form direct parent to child https://www.javascriptstuff.com/use-refs-not-ids/

But when routes come to picture i am a bit confused

like image 760
INFOSYS Avatar asked Jan 26 '26 13:01

INFOSYS


1 Answers

I think, you got a little confused with the use of ForwardRef. It is useful when you want to access the ref on a component which is wrapped by and HOC and not when you wish to pass on the ref of another component as props

What you need here is to pass on the ref with a different name to the child routes

myRef = (ref) => {
   this.secRef = ref;
}
<Overview>
    <div className={styles.container}>
      <HeaderComponent/>
      <SecondaryHeader section={this.state.section} ref = {myref}/> 
    </div>
    <div>
        <Routes fullScreenCB = {this.goToFullScreen} secRef={this.secRef}/>
    </div>
    <NetworkCheck/>
  </div>
</Overview>


const Routes = ({fullScreenCB, secRef}: IRouteProps) : React.ReactElement<IRouteProps> => {
      <Route exact path="/" render={() => <[withAuth(Home)] secRef={secRef} />} />
      <Route exact path="/about" render={() => <[withAuth(About)] secRef={secRef} />} />
      <Route exact path="/topics" render={() => <[withAuth(Topics)] secRef={secRef} />} />
})


myProtected Route HOC



export default (ProtectedRoute, fullScreenCB) => {


  class WrapperClass extends React.Component<any, {}> {
    constructor(props) {
      super(props);
      this.state = {
        isAuthenticated: process.env.NODE_ENV === "development" ? true : false
      };
    }

    render() {
      if (this.state.isLoading) {
        return (
          <div style={{width: "100%", height: "100%"}}>
              <CircularProgress style={{left: "50%", marginTop: "30%"}} size={"xlarge"}/>
          </div>
        )
      } else if (this.state.isAuthenticated) {
        let {forwardedRef, ...rest } = this.props;
        rest = {...rest, fullScreenCB};
        return (
          <ProtectedRoute
            ref={forwardedRef}
            {...rest}
          />
        )
      }
    }
  }

  let WrappedComponent = React.forwardRef(
    function withAuthorizationWarpper(props, ref) {
      return <WrapperClass {...props} forwardedRef={ref}/>;
    }
  );

  hoistNonReactStatic(WrappedComponent, ProtectedRoute);

  return WrappedComponent;
}

Once you implement it like above, you will be able to access SecondaryHeader's ref in the child component using this.props.secRef

P.S However its not a recommended way to pass on ref to other components, if there is some function or property that you wish to access in other components, its a better idea to lift those properties up to the common parent and pass them as props or via context to the required components

like image 184
Shubham Khatri Avatar answered Jan 29 '26 02:01

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!