Retrieving value in React

React provides controlled components where input values are managed by state, facilitating easy access to input values.

Syntax:

const [username, setUsername] = useState<string>('');
<input type="text" value={username}
onChange={(e) => setUsername(e.target.value)} />

Example: The below code will explain how you can get the value of input element in ReactJS.

JavaScript
import React, { useState } from 'react';

const App: React.FC = () => {
    const [username, setUsername] = useState<string>('');

    const handleInputChange = 
        (e: React.ChangeEvent<HTMLInputElement>) => {
            setUsername(e.target.value);
        };

        return (
        <div>
            <input type="text" value={username} 
                onChange={handleInputChange} 
                placeholder="Enter your username" />
            <p>Username: {username}</p>
        </div>
    );
};

export default App;

Output:



How to Get Value of Input in TypeScript ?

In TypeScript, retrieving the value of an input element is a common task when building web applications. Whether you’re handling form submissions, validating user input, or manipulating data based on user interactions, accessing input values is essential.

The below approaches can be utilized to get input value in TypeScript:

Table of Content

  • Using document.getElementById
  • Retrieving value in React

Similar Reads

Using document.getElementById

This approach involves using Vanilla JavaScript to access input elements by their IDs and then retrieving their values using the value property....

Retrieving value in React

React provides controlled components where input values are managed by state, facilitating easy access to input values....