I have a custom component using using forwardRef() and I use it multiple times
like this:
const CustomComp = React.forwardRef(({props...},{ref1,ref2})=>{...}); //this is in another file
const CombinedRef={ref1:useRef(),ref2:useRef()};
<CustomComp ref={CombinedRef}/> //case 1
<CustomComp/> //case 2
but there are occasions where the custom component doesn't need a ref like in the second case
but if I don't pass the ref in case 2 it gives an error
null is not an object
so far my only solution has been <CustomComp ref={{}}/> //case 2
but is there a way where I don't have to pass ref in case 2 ?
You cannot destructure your ref's directly if it should be an optional prop. So i shortly did a sandbox to show that... What you try right now is this:
const CustomComp = forwardRef((props, { ref1, ref2 }) => {
console.log("ref1", ref1);
console.log("ref2", ref2);
return (
<div {...props}>
<span>CustomComp</span>
</div>
);
});
When you try to render that like this:
export default function App() {
const ref1 = useRef();
const ref2 = useRef();
return (
<div className="App">
<CustomComp ref={{ ref1, ref2 }} />
<CustomComp />
</div>
);
}
You get the error TypeError: Cannot destructure property 'ref1' of 'object null' as it is null.
But if you change it to this:
const CustomComp = forwardRef((props, ref) => {
const { ref1, ref2 } = ref ? ref : {};
console.log("ref1", ref1);
console.log("ref2", ref2);
return (
<div {...props}>
<span>CustomComp</span>
</div>
);
});
Then it starts working ;-)
Here is the sandbox: https://codesandbox.io/s/agitated-worker-pqjn3?file=/src/App.js:68-296