index.js
index.html
import React from 'react';
import ReactDOM from 'react-dom';
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
mySubmitHandler = (event) => {
event.preventDefault();
let age = this.state.age;
if (!Number(age)) {
alert("Your age must be a number");
}
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<h1>Hello {this.state.username} {this.state.age}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={this.myChangeHandler}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={this.myChangeHandler}
/>
<br/>
<br/>
<input type='submit' />
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>