Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use forwarded ref and internal ref simultaneously in React

I have the following class for example:

class UserList extends React.Component {
   body = React.createRef();
   componentDidMount() {
      this.body.scrollTop = 100;
   }
   render() {
      <div ref={this.body}>
         ...
      </div>
   } 
}

We need to pass ref from outside, so I create the another component:

React.forwardRef((props, ref) => <UserList 
  innerRef={ref} {...props}
/>)

What's the right way to use this ref? Should I rewrite class like this:

class UserLists extends React.Component {
   body = React.createRef();
   componentDidMount() {
      this.getRef().current.scrollTop = 100;
   }
   getRef() {
      return (this.props.innerRef || this.body)
   }
   render() {
      <div ref={this.getRef()}>
         ...
      </div>
   } 
}

Maybe it's anti-pattern, because the passed ref might not contain current property (callback ref or string ref), so how should I solve this problem?

like image 454
nitrovatter Avatar asked Jan 24 '26 09:01

nitrovatter


1 Answers

Your code does not make sense, because you override the reference with .scrollTop so ref={this.body} is useless.

But here is a generic example of how to pass a reference:

class UserLists extends React.Component {
  render() {
    return <div ref={this.props.innerRef}>Hello</div>;
  }
}

const Forwared = React.forwardRef((props, ref) => {
  const defaultRef = useRef();
  return <UserLists innerRef={ref || defaultRef} {...props} />;
});

const App = () => {
  const ref = useRef();
  useEffect(() => {
    console.log(ref);
  }, []);
  return <Forwared ref={ref} />;
};

Edit jovial-currying-hegmz

like image 140
Dennis Vash Avatar answered Jan 25 '26 21:01

Dennis Vash



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!