createRef

Advertisement

  • We¬†can¬†create¬†the¬†reference¬†with¬†**createRef()**¬†function.
  • We¬†can¬†use¬†the¬†`ref`¬†parameter¬†to¬†set¬†the¬†reference.
  • We¬†can¬†use¬†the¬†same¬†reference¬†inside¬†our¬†componet.

E.g.

  • In¬†below¬†example,¬†We¬†have¬†created¬†a¬†reference¬†`input`¬†with¬†function¬†**createRef()**.
  • On¬†button¬†click¬†we¬†trigger¬†the¬†function¬†**clickHandler**
  • Inside¬†`clickHandler`¬†function¬†we¬†can¬†access¬†our¬†input¬†with¬†variable¬†`input`.
  • So,¬†We¬†have¬†set¬†the¬†value¬†`Clicked`¬†to¬†our¬†input¬†with¬†the¬†help¬†of¬†`input.current.value`.
  • We¬†can¬†access¬†our¬†`<input¬†type=”text”¬†..>`¬†with¬†the¬†help¬†of¬†reference.
import { createRef } from 'react';

const App = () => {

	// Create ref.
	let input = createRef();

	const clickHandler = () => {
		// Set value for input text.
		input.current.value = 'Clicked';
	}

	return (
		<div>
			<input ref={input} type="text" value="" />
			<button onClick={clickHandler}>Click me</button>
		</div>
	)
}

export default App;
%d bloggers like this: