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?
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} />;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With