Open In App

How to Change an Uncontrolled Input in React?

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Uncontrolled input refers to form elements such as text fields, checkboxes, or radio buttons, where the value isn't directly managed by the React state. Their values are stored within the DOM itself and are independent of the React state. It can be challenging to change their input. In this article, we will learn about how to change an uncontrolled input in React.

Using useRef Hook

useRef hook of react provides a way to directly access DOM elements. We are going to use useRef hook to change uncontrolled input. First, we are going to create a useRef and attach it to the input element, so we can access it. then by using current.value, we will update it's value.

Syntax:

//Import 
import React, { useRef } from 'react';

//Declare
const inputRef = useRef(null);

//Using
<input type="text" ref={inputRef} />

Creating React Application

Step 1: Create a React application using the following command.

npx create-react-app gfg

Step 2: After creating your project folder i.e. gfg, move to it using the following command.

cd gfg

Project Structure

react-structure_optimized_50
Folder Structur

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-bootstrap": "^2.9.2",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Approach:

  • Import useRef from React to create a mutable reference for accessing the input element.
  • Set up inputRef with useRef(null) to establish a reference that will directly manipulate the input element.
  • Create a function (handleClick) that updates the input's value by accessing inputRef.current.value and setting it to 'GeeksForGeeks'.
  • Assign inputRef to the ref attribute of the input element (<input type="text" ref={inputRef} />). This connects the input element with the inputRef reference.
  • Connect the handleClick function to a button’s onClick event. When clicked, it updates the input's value through the inputRef, demonstrating direct DOM manipulation in React.

Example: This example demonstrate to change an uncontrolled input in react.

JavaScript
/App.js

import React, { useRef } from 'react';

export function App() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.value = 'GeeksForGeeks';
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Change Value</button>
    </div>
  );
}

Output


Next Article
Article Tags :

Similar Reads