Get the input value on button click in React

0
16

In this tutorial, we are going to learn how to get the input value on button click in react with the help of examples.

Consider we have a component like this.

import React from "react";

function App() 
    return (
      <div>        <input placeholder="Enter name" />
        <button>Log value</button>
      </div>
    );

export default App;

Now, we need to get the above input field value by clicking on the button.

To get an input value on button click, define a state variable that tracks the input value and add a onChange event handler to it. Inside the event handler method update the state variable with the input value.

At last add a click event handler to the button and access the input value from the react state variable.

Here is an example:

import React,useState from "react";

function App()

const [name, setName] = useState("");

  const handleInputChange = (event) => 
    setName( name: event.target.value );
  ;

   handleBtnClick = () => 
    console.log(this.state.name);
  ;

    return (
      <div>
        <input  value=name onChange=this.handleInput/>
        <button onClick=handleBtnClick>Log value</button>
      </div>
    );

In the above code, we are storing the input field value inside the name property. So, whenever the input value is changed it updates the name property using the setName( name: event.target.value );.

If we click on a button it logs the input value from the react state.

Get input value on button click using react refs

Similarly, we can use the useRef hook in react to get the input field value on button click.

Example:

import React,  useRef  from "react";

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

  handleBtnClick = () => 
    console.log(nameRef.current.value);
  ;

  return (
    <div>
      <input ref=inputRef placeholder="Enter name"/>
      <button onClick=logValue>Log value</button>
    </div>
  );

In the above code, we first initialized the useRef() hook with a value null and passed it to the input element using the ref=inputRef. So it returns an input element dom node just like document.getElementByid().

Now, we can access the input value using the nameRef.current.value.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here