Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 790

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T02:09:06+00:00 2024-11-25T02:09:06+00:00

Understanding the use of useRef hook & forwardRef in React

  • 62k

The useRef hook in react is used to create a reference to an HTML element. Most widely used scenario is when we have form elements and we need to reference these form elements to either print their value or focus these elements etc.

So the {useRef} hook is imported from “react” like other react hooks and we use them inside functional components to create references and this can be assigned to an html element in the jsx by using the “ref” attribute.

An example for using the useRef hook is shown below-

  import React, { useEffect, useRef } from "react";  const UseRefHookExplained = (props) => {   // Creating refs for username and password   const userNameRef = useRef(null);   const passwordRef = useRef(null);    // We are also creating a reference to the Login button   const submitBtnRef = useRef(null);    // useEffect to set the initial focus to the user name input   useEffect(() => {     userNameRef.current.focus();   }, []);    // This function is used to handle the key press.   // Whenever user hits enter it moves to the next element   const handleKeyPress = (e, inputType) => {     if (e.key === "Enter") {       switch (inputType) {         // Checks if Enter pressed from the username field?         case "username":           // Moves the focus to the password input field           passwordRef.current.focus();           break;         // Checks if Enter pressed from the password field?         case "password":           // Moves the focus to the submit button           submitBtnRef.current.focus();           e.preventDefault();           break;         default:           break;       }     }   };    // Function to handle the submit click from the button   const handleSubmit = () => {     alert("submitted");   };    // getting the style as prop from the parent.   // Basic style to center the element and apply a bg color   const { style } = props;   return (     <div style={style}>       <h2>Example for using useRef Hook</h2>       <h3>Login</h3>       <input         type="text"         name="username"         ref={userNameRef}         onKeyDown={(e) => handleKeyPress(e, "username")}       />       <input         type="password"         name="password"         ref={passwordRef}         onKeyDown={(e) => handleKeyPress(e, "password")}       />       <button ref={submitBtnRef} onClick={handleSubmit}>         Login       </button>     </div>   ); };  export default UseRefHookExplained;     
Enter fullscreen mode Exit fullscreen mode

So the concept of useRef hook is straight forward as you can see in the above code. Follow the following steps –

  1. We import useRef hook from react
  2. We initialize this hook (eg: const inputRef = useRef(null))
  3. The reference created is attached to an html element using the “ref” attribute.

Now we will have a reference to this element readily available to be used to make changes like getting the value, focusing etc

Output
Initial state when the page loads –
image.png

Focus State after entering user name and pressing enter –
image.png

Focus state moving to the button after entering the password and clicking on Enter

image.png

So, this much should be pretty clear by now. Now let us look at a scenario when we will be using another React component for input.

In this case it becomes a little difficult to pass on the reference that we have defined in the parent component as a property to the child (Input component).

React provides us a way to handle this scenario and forward the refs to the child component using React.forwardRef

Let us check the example code to see the changes –
( I have added a comment “//new” to identify the newly added lines)

  import React, { useEffect, useRef } from "react"; import Input from "./Input"; // new  const UseRefHookExplained = (props) => {   // Creating refs for username and password   const userNameRef = useRef(null);   const passwordRef = useRef(null);    // We are also creating a reference to the Login button   const submitBtnRef = useRef(null);    // useEffect to set the initial focus to the user name input   useEffect(() => {     userNameRef.current.focus();   }, []);    // This function is used to handle the key press.   // Whenever user hits enter it moves to the next element   const handleKeyPress = (e, inputType) => {     if (e.key === "Enter") {       switch (inputType) {         // Checks if Enter pressed from the username field?         case "username":           // Moves the focus to the password input field           passwordRef.current.focus();           break;         // Checks if Enter pressed from the password field?         case "password":           // Moves the focus to the submit button           submitBtnRef.current.focus();           e.preventDefault();           break;         default:           break;       }     }   };    // Function to handle the submit click from the button   const handleSubmit = () => {     alert("submitted");   };    // getting the style as prop from the parent.   // Basic style to center the element and apply a bg color   const { style } = props;   return (     <div style={style}>       <h2>Example for using useRef Hook</h2>       <h3>Login</h3>       {/* New. Using the Component instead of input element */}       <Input         type="text"         name="username"         ref={userNameRef}         onKeyDown={(e) => handleKeyPress(e, "username")}       />       {/* New. Using the Component instead of input element */}       <Input         type="password"         name="password"         ref={passwordRef}         onKeyDown={(e) => handleKeyPress(e, "password")}       />       <button ref={submitBtnRef} onClick={handleSubmit}>         Login       </button>     </div>   ); };  export default UseRefHookExplained;    
Enter fullscreen mode Exit fullscreen mode

Now let us look at the Input.js component

  import React from "react";  /* In the functional component, a second argument  is passed called ref, which will have access to  the refs being forwarded from the parent */ const Input = (props, ref) => {   /* assigning the ref attribute in input and spreading  the other props which will contain type, name, onkeydown etc */   return <input {...props} ref={ref} />; };  // wrapping the Input component with forwardRef const forwardedRef = React.forwardRef(Input);  // Exporting the wrapped component export default forwardedRef;    
Enter fullscreen mode Exit fullscreen mode

So, React.forwardRed provides us a way with which we can still pass on or forward the refs defined in the parent component to the child component.

Hope you learned something new today!

javascriptreacttutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.