Get the input value on button click in React
In this post we will give you information about Get the input value on button click in React. Hear we will give you detail about Get the input value on button click in ReactAnd how to use it also give you demo for it if it is necessary.
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> );}<span>export default App;
Now, we need to get the above input field value by clicking on the button.
To get a 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 variabale.
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 buton 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 a input element dom node just like document.getElementByid().
Now, we can access the input value using the nameRef.current.value.
Hope this code and post will helped you for implement Get the input value on button click in React. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs