custom component માટે પસાર થયેલ ref તેની અંદર DOM નોડ સુધી આપોઆપ પહોંચતો નથી. forwardRef કમ્પોનેન્ટને ref મેળવવા અને તેને બાળ તત્વ સાથે જોડવા દે છે. useImperativeHandle તે ref શું કરે છે તે કસ્ટમાઇઝ કરે છે.
custom component માટે પસાર થયેલ ref તેની અંદર DOM નોડ સુધી આપોઆપ પહોંચતો નથી. forwardRef કમ્પોનેન્ટને ref મેળવવા અને તેને બાળ તત્વ સાથે જોડવા દે છે. useImperativeHandle તે ref શું કરે છે તે કસ્ટમાઇઝ કરે છે.
const TextInput = forwardRef(function TextInput(props, ref) {
return <input ref={ref} {...props} />; // parent's ref now points to the <input>
});
// parent can focus the inner input:
const ref = useRef(null);
<TextInput ref={ref} />;
// ref.current.focus();
કેટલીકવાર તમે સમગ્ર DOM નોડ લીક કરવા નથી માંગતા — માત્ર specific methods:
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inner = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inner.current.focus(),
clear: () => { inner.current.value = ""; },
}), []);
return <input ref={inner} {...props} />;
});
// parent: fancyRef.current.focus(); fancyRef.current.clear();
communication માટે props/state પસંદ કરો. Refs માટે તેમજ માત્ર સાચું imperative જરૂરિયાતો માટે: focus management, scrolling, text selection, media playback, અથવા imperative libraries એકીકરણ. નોટ: React 19 માં, ref સામાન્ય prop તરીકે પસાર કરી શકાય છે, તેથી forwardRef મોટાભાગે વધુ જરૂરી નથી.
વિગતવાર જવાબો સાથે IT ઇન્ટરવ્યૂ પ્રશ્નોની લાઇબ્રેરી — જુનિયરથી સિનિયર સુધી.
દાન કરો