Minimal react form
by everdimension
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto+Slab" rel="stylesheet">
<div id="app"></div>
SCSS
body {
font-family: 'Roboto Slab', sans-serif;
background: white;
color: #484848;
padding: 40px;
}
input {
display: block;
margin-bottom: 15px;
margin-top: 5px;
padding: 10px;
border: 1px solid #cfcfcf;
font-family: 'Roboto Slab', sans-serif;
font-size: 16px;
outline: none;
}
pre, code {
font-family: 'Roboto Mono', Monaco;
}
button {
cursor: pointer;
padding: 12px;
background: #999;
font-family: 'Roboto Slab', sans-serif;
font-size: 16px;
border: none;
outline: none;
color: white;
border-bottom: 2px solid #797979;
&:hover {
background-color: #a1a1a1;
}
&:active {
background-color: #888;
}
}
form {
display: inline-block;
margin-right: 50px;
vertical-align: top;
}
.res-block {
display: inline-block;
}
h3 {
margin-top: 0;
}
Babel + JSX
class MyForm extends React.Component {
constructor() {
super();
this.state = {};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
this.setState({
res: stringifyFormData(data),
});
// fetch('/api/form-submit-url', {
// method: 'POST',
// body: data,
// });
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="birthdGate">Enter your birth date</label>
<input id="birthdate" name="birthdate" type="text" />
<button>Send data!</button>
</form>
{this.state.res && (
<div className="res-block">
<h3>Data to be sent:</h3>
<pre>FormData {this.state.res}</pre>
</div>
)}
</div>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('app'));
function stringifyFormData(fd) {
const data = {};
for (let key of fd.keys()) {
data[key] = fd.get(key);
}
return JSON.stringify(data, null, 2);
}