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
Click to Enlarge