trainReact.com
||

2. Input With Auto Focus

Easy
Category: Hooks
useRefinput

Problem Description

You are given a React component AutofocusInput that renders an input field with a label and a p tag that should display the current input value.

Your task is to implement the functionality where the input field is automatically focused when the component renders, and the input value is updated and displayed as the user types.

Whitespace should be removed from the beginning and end of the input value.

Requirements

  1. The component should render an input field with a label "Enter your name:".
  2. The input field should be automatically focused when the component renders.
  3. As the user types, the current value should be displayed below the input field.
  4. Whitespace should be removed from the beginning and end of the input value.
  5. The component should handle empty input correctly.
  6. The input should maintain focus after value changes.

Constraints

  • Do not modify the existing JSX structure or data-testid attributes.
  • Use the provided data-testid attributes for the input field ('inputField') and the paragraph displaying the current value ('pInputValue').
import React, {useState} from 'react';

function InputAutoFocus () {
  const [inputValue, setInputValue] = useState('');

  return (
    <div>
      <label htmlFor="nameInput">Enter your name:</label>
      <input
        id="nameInput"
        data-testid="inputField"
        type="text"
      />
      <p data-testid="pInputValue">Current value: {inputValue}</p>
    </div>
  );
};

export default InputAutoFocus;

Open browser consoleTests