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

Get the value of an Input on Button click in React

This article will show you how to get the value of an input on Button click in React using the state method or useRef hook. Read on it now.

Get the value of an input on Button click in React

Use state to store the value of the input

This way, we will use the useState hook to store the value of the input and change it on the input’s onChange event. To get the input value when we press the button, we will call the state to save that value. Check out the example below to see how it works.

Code:

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

Output:

As you can see, when we use state and assign the input value to point to it, you can access it anywhere in the component. In the above example, we listen to the button’s onClick event and alert input value to the screen.

Use useRef() method

UseRef is like a “box” used to store the values ​​of an element using the .current attribute. You are probably familiar with ref primarily as a way to access the DOM. So we can use it with the input that needs to get the value like 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="name"
        name="name"
        placeholder="Enter your name..."
        ref={inputRef}
      />
      <button
        onClick={() => {
          alert(inputRef.current.value);
        }}
      >
        Show input value
      </button>
    </>
  );
};
 
export default App;

Notice at the beginning of the code we have declared a ref named inputRef from the useRef() hook. We then assign it to the input we want to point to, along with the ref. current. value syntax so we can get the value of the input when the button is pressed. The returned result is the same as above. I wish you success with the methods in the article.

Summary

To summarize, we have gone through some ways to get the value of an Input on Button click in React, but I recommend using the useRef method because it will help you to call the input everywhere in components.

Maybe you are interested:

Leave a Reply

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