Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import axios from 'axios';
- import _ from 'lodash';
- const ROOT_URL = 'http://localhost:3001/api/v1';
- const FIELDS = {
- fullname: {
- type: 'input',
- name: 'fullname',
- label: 'Name'
- },
- position: {
- type: 'input',
- name: 'position',
- label: 'Position'
- },
- address: {
- type: 'textarea',
- name: 'address',
- label: 'Address'
- },
- phone: {
- type: 'input',
- name: 'phone',
- label: 'Phone'
- }
- }
- class CreateStaff extends Component {
- constructor(props) {
- super(props);
- this.state = {
- fields: {
- fullname: '',
- position: '',
- address: '',
- phone: ''
- }
- };
- this.handleSubmit = this.handleSubmit.bind(this);
- this.handleChange = this.handleChange.bind(this);
- this.renderField = this.renderField.bind(this);
- }
- renderField(fieldConfig) {
- return(
- <div className="form-group" key={fieldConfig.name}>
- <label className="col-sm-2 control-label">{fieldConfig.label}</label>
- <div className="col-sm-10">
- {/* how to use value={this.state.fields[iterate_key_here]} in this iteration method */}
- <fieldConfig.type type="text" className="form-control" value={this.state.fields[key_here]} name={fieldConfig.name} onChange={this.handleChange}/>
- </div>
- </div>
- );
- }
- handleChange(e) {
- const state = this.state.fields;
- state[e.target.name] = e.target.value;
- this.setState(state);
- }
- handleSubmit(e) {
- e.preventDefault();
- // get form data out of state
- const { fullname, position, address, phone } = this.state.fields;
- axios
- .post(`${ROOT_URL}/staff`, { fullname, position, address, phone })
- .then((res) => {
- console.log(res);
- });
- }
- render() {
- return(
- <div className="container" onSubmit={this.handleSubmit}>
- <form className="form-horizontal">
- {/* === Generate fields === */}
- {
- _.map(FIELDS, this.renderField)
- }
- <div className="form-group">
- <div className="col-sm-offset-2 col-sm-10">
- <button type="submit" className="btn btn-success">Save</button>
- </div>
- </div>
- </form>
- </div>
- );
- }
- }
- export default CreateStaff;
Advertisement
Add Comment
Please, Sign In to add comment