forwardRef

Advertisement

  • With¬†`createRef()`¬†we¬†can¬†access¬†any¬†element¬†with¬†reference.
  • Same¬†way¬†we¬†can¬†forward¬†the¬†reference¬†of¬†element¬†from¬†one¬†compoent¬†to¬†another¬†with¬†**forwardRef()**

E.g.

  • In¬†below¬†example¬†we¬†have¬†a¬†`<App>`¬†component.
  • We¬†have¬†created¬†the¬†refernence¬†`input`¬†with¬†**createRef()**.
  • And¬†assign¬†the¬†refrence¬†with¬†`ref`¬†attribute¬†as¬†`ref={input}`.
  • We¬†have¬†another¬†component¬†`<Button¬†ref={input}¬†/>`¬†in¬†which¬†we¬†have¬†pass¬†the¬†input¬†reference.
  • We¬†have¬†created¬†the¬†`<Button>`¬†component¬†with¬†`forwardRef()`¬†function.
  • It¬†accept¬†**props,¬†ref**¬†parameters.
  • The¬†`ref`¬†parameter¬†reference¬†to¬†our¬†`input`¬†field.
  • On¬†Click¬†on¬†button¬†we¬†trigger¬†the¬†function¬†`clickHandler`.
  • And¬†finally¬†we¬†set¬†the¬†value¬†to¬†our¬†input¬†with¬†`ref.current.value`.
  • So,¬†On¬†click¬†on¬†button¬†we¬†can¬†see¬†the¬†value:¬†**with¬†forwardRef()**.
import { createRef, forwardRef } from 'react';

const Button = forwardRef( ( props, ref ) => {

    const clickHandler = () => {
		// Set value for input text.
		ref.current.value = 'with forwardRef()';
    }
    
    return (
        <button onClick={clickHandler}>Click me</button>
    )
} );

const App = () => {

	// Create ref.
    let input = createRef();
    
	return (
		<div>
			<input ref={input} type="text" value="" />
			<Button ref={input} />
		</div>
	)
}

export default App;
%d bloggers like this: