Exercise: useRef
by Tomas Trescak· Advanced React

0 / 3310 XP

Objective:

Students will build a simple form where they use the useRef hook to focus an input field and display its current value.


Starter Code:

import React, { useRef, useState } from 'react';

function RefForm() {
  const [value, setValue] = useState("");

  const handleFocus = () => {
    // TODO: Use inputRef to focus the input field
  };

  const handleDisplayValue = () => {
    // TODO: Use inputRef to display the current input field value
  };

  return (
    <div>
      <input type="text" placeholder="Type something..." />
      <button onClick={handleFocus}>Focus Input</button>
      <button onClick={handleDisplayValue}>Display Value</button>
      <p>Current Value: {value}</p>
    </div>
  );
}

Task Requirements:

  1. Focus on Input Field:
    Complete the handleFocus function to make the input field focused when the "Focus Input" button is clicked.
  2. Display Current Value:
    Complete the handleDisplayValue function to display the current value of the input field in the <p> tag.
  3. Enhancements (Optional):
    • Clear the input field after displaying the value.
    • Add a character counter below the input.
OBJECTIVE: Students will build a simple form where they use the useRef hook to focus an input field and display its current value. -------------------------------------------------------------------------------- STARTER CODE: import React, { useRef, useState } from 'react'; function RefForm() { const [value, setValue] = useState(""); const handleFocus = () => { // TODO: Use inputRef to focus the input field }; const handleDisplayValue = () => { // TODO: Use inputRef to display the current input field value }; return ( <div> <input type="text" placeholder="Type something..." /> <button onClick={handleFocus}>Focus Input</button> <button onClick={handleDisplayValue}>Display Value</button> <p>Current Value: {value}</p> </div> ); } -------------------------------------------------------------------------------- TASK REQUIREMENTS: 1. Focus on Input Field: Complete the handleFocus function to make the input field focused when the "Focus Input" button is clicked. 2. Display Current Value: Complete the handleDisplayValue function to display the current value of the input field in the <p> tag. 3. Enhancements (Optional): * Clear the input field after displaying the value. * Add a character counter below the input.

Discuss with Others
Ask questions, share your thoughts, and discuss with other learners

Join the discussion to ask questions, share your thoughts, and discuss with other learners
Loading...
Ready ...
Content Locked
This content is only available to registered users.
Please register at the the home page.
Setup
React Fundamentals
10 points
Next.js
10 points
Advanced React
Databases
10 points
React Hooks
Authentication and Authorisation
10 points
APIs
CI/CD and DevOps
Testing React
Advanced Topics