API form submit
by Amir Danish
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/1.1.0-rc.0/react-bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.0.0/fetch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsonform/2.2.0/jsonform.js"></script>
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
name:'',
email:''
};
}
handleChange =(event)=> {
this.setState({
[event.target.name]: event.target.value});
}
handleSubmit =(event)=>{
event.preventDefault();
fetch('url',{
method: 'POST',
body: json(this.state)
}).then(function(res){
console.log(res)
return res.json();
})
event.target.reset();
/* fetch('http://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then((data) => {
this.setState({ contacts: data })
})
.catch(e => e instanceof TypeError && e.message === "Failed to fetch" ?
({status: 504}) : // Workaround for chrome; which simply fails with a typeerror
Promise.reject(e))
*/
}
render() {
return (
<div>
<h2>Sumit form to API</h2>
<form onSubmit={this.handleSubmit}>
<input name="name" type="text" value={this.state.value} onChange={this.handleChange} placeholder="David ..." required />
<input name="email" type="text" value={this.state.value} onChange={this.handleChange} placeholder="[email protected] ..." required />
<button type="submit">Submit</button>
</form>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))