How to set the value of an input on Button click in React

Set the value of an Input on Button click in React

This article will give you some ways to set the value of an Input on Button click in React using the useRef method or the state method. Let’s read it now to get more knowledge.

Set the value of an input on button click in React

Use useRef() hook method

The current attribute is used to store the values of an element using useRef, which is similar to a “box”. Most likely, your primary use of ref is to access the DOM. Therefore, we can utilize it with the required input to set the new value. Look at the following code.

Code:

import React from "react";
import { useRef } from "react";
 
const App = () => {
  const inputRef=useRef();
  return (
    <>
      <h2>Get the value of an Input on Button click in React | LearnShareIT</h2>
      <input
        type="text"
        id="website"
        name="website"
        placeholder="Enter your website..."
        ref={inputRef}
      />
      <button
        onClick={() => {
         inputRef.current.value="LearnShareIT";
        }}
      >
        Set input value
      </button>
    </>
  );
};
 
export default App;

Output:

By adding the ref attribute value to the input, we could point to the input that needed to change the value. The object returned by this ref can be accessed on the value using the ref. current.value method so that this value can be retrieved and modified.

Use the useState hook method

We will do this by storing the input’s value and changing it on the input’s onChange event using the useState hook. We will call the state to save the input value to set it when we press the button. To see how it works, see the example below.

Code:

import React from "react";
import { useState } from "react";
 
const App = () => {
  const [inputValue, setInputValue] = useState("");
  return (
    <>
      <h2>Set the value of an Input on Button click in React | LearnShareIT</h2>
      <input
        type="text"
        id="name"
        name="name"
        placeholder="Enter your name..."
        value={inputValue}
      />
      <button
        onClick={() => {
         setInputValue("LearnShareIT");
        }}
      >
        Set input value
      </button>
    </>
  );
};
 
export default App;

When you initialize the state to hold the value of the input with useState. You also have a default method we named setInputValue() that can set the value of this input. So you can call this method when the Set input value button is clicked to set the value of an input on Button click as we need to do. Good luck with the above two methods.

Summary

To recap, the article has shown you several ways to set the value of an input on Button click in React. Still, you should use the useRef method because it will be more flexible and accessible to all elements that only need ref.current.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *