React Get Input Value on Button Click

React Js Get value of Input Field on Button click:In ReactJS, to obtain the value of an input field upon a button click, you need to create a controlled component. This involves setting up the input field's value as a state variable using React's useState hook. Attach an onChange handler to the input to update the state as the user types. Then, on button click, access the stored state value. This approach ensures synchronization between UI and state. In summary, by establishing a controlled input with state management, you can capture the input's value accurately when the button is clicked.




Thanks for your feedback!
Your contributions will help us to improve service.
How can you retrieve the value of an input field in Reactjs when a button is clicked?
This React JS script sets up an input field and a button. The input's value is managed by a state variable inputValue
. When the input changes, the handleInputChange
function updates the state. Clicking the button triggers handleButtonClick
, which logs the current input value to the console. The HTML renders a container with a title, input, and button. The input's value is bound to inputValue
, and its changes trigger handleInputChange
. The button's click event is linked to handleButtonClick
. Overall, this captures and displays the input value on button click.
React Get Input Value on Button Click Example
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [inputValue, setInputValue] = useState(''); // State to store input value
const handleInputChange = (event) => {
setInputValue(event.target.value); // Update input value in state
};
const handleButtonClick = () => {
console.log('Input value:', inputValue); // Log the input value when button is clicked
};
return (
<div className='container'>
<h3>React Js Get value of Input Field on Button click</h3>
<input type="text" value={inputValue} onChange={handleInputChange} />
<button onClick={handleButtonClick}>Get Value</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>