react get input value on submit code example
Example 1: react text input onchange
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} /> </label>
<input type="submit" value="Submit" />
</form>
);
}
}
Example 2: handle onchange react
import React, { Component } from 'react';
import './App.css';
import Header from './Header';
class App extends Component {
constructor(props) {
super(props);
this.state = {name: "Michael"}
}
changeTitle = (e) =>{
this.setState({name: e.target.value});
}
render() {
return (
<div className="App">
<Header title={this.state.name}/>
<p className="App-intro">
Type here to change name.
<input type="text" onChange={this.changeTitle}/>
</p>
</div>
);
}
}
export default App;
Example 3: input text react 2020
function LoginForm() {
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
api.login(email, password);
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</form>
);
}