Articles → REACT.JS → Display error messages in react.js

Display error messages in react.js






Example






import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';


class FormComponent extends React.Component {

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

    }

   

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

        
        
    }

    mySubmitHandler = (event) => {
        if (this.state.name.length > 5) {
            event.preventDefault();
            this.setState({ error: "length is more" });
            return;
        }
        alert("You are submitting " + this.state.name);
    }

    render() {
        return (
            <form onSubmit={this.mySubmitHandler}>
                <label className="alert alert-danger">{ this.state.error}</label><br/>
                Name: <input type="text" name="txtName" onChange={this.myChangeHandler}/>
                <input type="submit" value="Click Me" />
            </form>
        );
    }
}

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



Output


Picture showing how to display error messages in react.js

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, August 21, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250