Last active
September 9, 2019 13:18
-
-
Save HelloAlberuni/f7a23b874ed90020f809fde7183a8a9c to your computer and use it in GitHub Desktop.
Reast: Submit form data to server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component } from 'react' | |
| import './App.css'; | |
| import PostForm from './PostForm' | |
| class App extends Component{ | |
| render(){ | |
| return ( | |
| <div className="container"> | |
| <div className="col-md-10"> | |
| <PostForm /> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| } | |
| export default App |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component } from 'react' | |
| import axios from 'axios' | |
| const BASE_URL = 'https://jsonplaceholder.typicode.com' | |
| class PostForm extends Component{ | |
| state = { | |
| title: '', | |
| body: '', | |
| userId: 112, | |
| isSubmitted: false, | |
| error: false | |
| } | |
| changeHandler = (event) => { | |
| this.setState({ | |
| [event.target.name]: event.target.value | |
| }) | |
| } | |
| submitHandler = (event) => { | |
| event.preventDefault(); | |
| axios.post(`${BASE_URL}/posts`, { | |
| title: this.state.title, | |
| body: this.state.body, | |
| userId: this.state.userId | |
| }) | |
| .then(response => { | |
| this.setState({ | |
| isSubmitted: true, | |
| error: false | |
| }) | |
| console.log(response); | |
| }) | |
| .catch(error => { | |
| this.setState({ | |
| error: true, | |
| isSubmitted: false | |
| }) | |
| }) | |
| } | |
| render(){ | |
| return( | |
| <div className='container'> | |
| <div className="row"> | |
| <form action="" onSubmit={this.submitHandler}> | |
| <label htmlFor="">Title</label> | |
| <input | |
| type="text" | |
| name="title" | |
| className="form-control" | |
| id="" | |
| value={ this.state.title } | |
| onChange={ this.changeHandler } | |
| /> | |
| <label htmlFor="">Desc</label> | |
| <textarea | |
| name="body" | |
| id="" | |
| className="form-control" | |
| cols="30" | |
| rows="10" | |
| onChange={ this.changeHandler } | |
| > | |
| { this.state.body } | |
| </textarea> | |
| <button type="submit" className="btn btn-primary">Submit</button> | |
| {this.state.isSubmitted && <p>Form subbmitted successfully</p>} | |
| {this.state.error && <p>Form Error</p>} | |
| </form> | |
| </div> | |
| </div> | |
| ) | |
| } | |
| } | |
| export default PostForm; | |
| // controlled form - Handle form data by state | |
| // uncontrolled form - process everything by submit handler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment