Explain Codes LogoExplain Codes Logo

How to get the value of an input field using ReactJS?

javascript
react-hooks
state-management
best-practices
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

Effectively fetch the value of an input field in React by leveraging controlled components. Link the input state through value and synchronize it via the onChange event. The basic paradigm is illustrated below:

class InputComponent extends React.Component { state = { value: '' }; handleValueChange = (event) => this.setState({ value: event.target.value }); render() { // Ever seen state and input having a romantic dance? Here it is! return <input value={this.state.value} onChange={this.handleValueChange} />; } }

This chunk of code births a text input field synchronized with the component's state.

A journey through alternative avenues

Dancing with React hooks using useState

Introduced in React 16.8, the useState hook revolutionized state management in functional components - it was like giving Spiderman a new suit.

import React, { useState } from 'react'; function InputComponent() { const [value, setValue] = useState(''); function handleValueChange(event) { //State becomes "newValue", can you hear the wedding bells? :) setValue(event.target.value); } return <input value={value} onChange={handleValueChange} />; }

Embracing useRef for uncontrolled components

Occasionally, an unpredictable yet adorable kid, useRef comes to our rescue, especially when you just want to steal a 'one-off' value.

import React, { useRef } from 'react'; function InputComponent() { const inputRef = useRef(); function handleSubmit(event) { event.preventDefault(); // Shhhh! Stealing a one-off value console.log(inputRef.current.value); } return ( <form onSubmit={handleSubmit}> <input ref={inputRef} type="text" /> <button type="submit">Submit</button> </form> ); }

Systemizing with standalone components

Breaking down your components, particularly in large applications, leads to clarity like the sun's rays piercing through clouds.

function EmailInput({ value, onChange }) { // An input handling email like a pro return <input type="email" value={value} onChange={onChange} />; } function App() { const [email, setEmail] = useState(''); return <EmailInput value={email} onChange={e => setEmail(e.target.value)} />; }

Debugging to catch red handed

Implement console.log within your onChange handler to ensure your values are updating as expected:

function handleValueChange(event) { console.log(event.target.value); // Echoing every keystroke, isn't that fun? setValue(event.target.value); }

Cultivating best practices

Arrange your code and state management practices for sustainability and ease of future maintenance.

Unleashing Form Powers and Evading Pitfalls

Event handling and function context

In class components, make sure your event handlers are not lost in "context":

constructor(props) { super(props); this.handleValueChange = this.handleValueChange.bind(this); }

Or arrow functions can be your fairy godmother, binding this for you:

handleChangeValue = (event) => { this.setState({ value: event.target.value }); // With Power of "this", I have the Power! };

Fortifying against default form submissions

In a typical React form, you'd want to deflect the default submission like a superhero to handle the submission yourself.

handleSubmit = (event) => { event.preventDefault(); // Not today, form! // Do something magnificent with state now };

Input types: a type for every occasion

Ensure the type attribute is defined accurately in your input. Choosing between "text" or "number" might just be your game-changing move.

Embracing React's evolving nuances

Stay on track with the latest on React's development by indulging in the official documentation. This ensures your code stays young and fresh — a bit like Benjamin Button.