Get User Input in ReactJS Application

We know that ReactJS is used to create the View part of our application.

In this article, we will create a TextBox and get that data in state, and use it to set the value property of the TextBox.

Create a new react application. Delete all the files from src folder EXCEPT index.js

Replace the existing code with the below code in index.js file

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    state = { name: '' };
    render() {
        return (
            < div >
                Enter your name: <input type="text" value=   {this.state.name} onChange={e => this.setState({ name:e.target.value })} />
                <div>Hi {this.state.name}!</div>
            </div >
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

In this, whatever the user writes in the TextBox, it gets stored in state and then assigned to the value property of the TextBox.
We can then use this state value wherever we want. In this example, we are simply displaying it in another div.

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started