Why You Shouldn't Use ref in React Props
When using ref in React, especially with forwardRef, it's important to understand how ref works — and how it doesn't.
The Problem
You might see this warning in your console:
refis not a prop. Trying to access it will result inundefinedbeing returned...
This usually happens when you try to declare ref in your component's propTypes or access it like a normal prop (props.ref). But ref is a special prop in React. It doesn't behave like other props.
✅ The Correct Way to Use ref
When using forwardRef, React gives the ref as the second argument of your function. Here's what that looks like:
const MyComponent = forwardRef(function MyComponent(props, ref) {
// use ref directly
});
Don't try to access ref through props.ref. That won't work.
❌ Don't Do This
MyComponent.propTypes = {
// This will trigger a warning!
ref: PropTypes.any,
};
React doesn't pass ref through the normal props object, so it shouldn’t be validated with propTypes.
The Fix
- Use
refonly via the second argument inforwardRef. - Remove
reffrompropTypes.
This will prevent the warning and adhere to React best practices.
Comments