Articles → REACT.JS → Forms In React.Js

Forms In React.Js






Forms




import React, { Component } from 'react';
import ReactDOM from 'react-dom'

class FormComponent extends React.Component {



    render() {
        return (
            <form>
                Name: <input type="text" name="txtName" /></form>
        );
    }
}

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





Output


Picture showing the output of form in react.js
Click to Enlarge


Handling The Submit Action




import React, { Component } from 'react';
import ReactDOM from 'react-dom'

class FormComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = { name: '' };

    }

    myChangeHandler = (event) => {
        this.setState({ name: event.target.value });
    }

    mySubmitHandler = (event) => {
        alert("You are submitting " + this.state.name);
    }

    render() {
        return (
            <form onSubmit={this.mySubmitHandler}>
                Name: <input type="text" name="txtName" onChange={this.myChangeHandler}/><input type="submit" value="Click Me" /></form>
        );
    }
}

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


Picture showing how to handle submit action in form in react.js
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, August 18, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250