Articles → REACT.JS → Refs In React.Js
Refs In React.Js
Purpose
Example
import React, { Component, useRef } from 'react';
import ReactDOM from 'react-dom'
const Home = () => {
const nameInputRef = useRef();
const handleClick = () => {
alert(nameInputRef.current.value);
}
return (
<form >
Name:
<input type="text" name="txtName" ref={nameInputRef} />
<button onClick={handleClick}>Click Me</button>
</form>
);
}
ReactDOM.render(<Home />, document.getElementById('root'));
- Initializing ref and assigning the value to the nameInputRef variable
- Set the ref property of the textbox
- Get the value of the textbox using the current.value
Output
Click to Enlarge