trainReact.com
||

5. Input Focus on Button Click

Easy
Category: Hooks
inputuseRef

Problem Description

You are given a React component InputFocusOnClick that renders two input fields and a button. Your task is to implement the functionality where clicking the button focuses the user input on the first input field.

What You Need to Implement

  1. Use the useRef hook.
  2. Implement a handleFocus function.
  3. Attach the handleFocus function to the button's onClick event.

Requirements

  1. The component should render two input fields and a button.
  2. Clicking the "Focus First Input" button should focus on the first input field.
  3. The second input field should remain unaffected by the focus button.
  4. Use the provided data-testid attributes for the inputs and button.

Constraints

  • Do not modify the existing JSX structure or data-testid attributes.
const InputFocusOnClick = () => {

  // TODO:
  
  return (
    <div>
      <label htmlFor="input1">First Input:</label>
      <input
        id="input1"
        type="text"
        data-testid="input1"
      />
      <br />
      <label htmlFor="input2">Second Input:</label>
      <input
        id="input2"
        type="text"
        data-testid="input2"
      />
      <br />
      <button data-testid="focus-button">
        Focus First Input
      </button>
    </div>
  );
};

export default InputFocusOnClick;

Open browser consoleTests