Here is my custom component with forwardRef. The ref is required in the component inside codes but it's optional for the parent component to send it as a prop
const MyComponent = React.forwardRef((props, ref) => {
const handleButtonClick = () => {
// I need to access the ref here but, it's null
// when I not pass ref as prop to my component
}
return (
<>
<input type="text" ref={ref}/>
<button onClick={handleButtonClick}>Click</button>
</>
)
})
How should I handle this? I want to have an optional ref as a prop also it's required inside.
Also, I tried to use the useRef in my component and pass the forwarded ref as its initial value, in that case, I could not reach the ref in my parent component.