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'));




  1. Initializing ref and assigning the value to the "nameInputRef" variable.
  2. Set the "ref" property of the textbox.
  3. Get the value of the textbox using the "current.value".

Output


Picture showing the output of refs in react.js

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, October 28, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250