|
| 1 | +import React from "react"; |
| 2 | +import PropTypes from "prop-types"; |
| 3 | +import axios from "axios"; |
| 4 | +import "./styles.css"; |
| 5 | + |
| 6 | +/** |
| 7 | + * @component Form |
| 8 | + * @props |
| 9 | + */ |
| 10 | +class Form extends React.Component { |
| 11 | + constructor(props) { |
| 12 | + super(props); |
| 13 | + this.state = { |
| 14 | + fname: "", |
| 15 | + lname: "", |
| 16 | + email: "", |
| 17 | + message: "", |
| 18 | + mailSent: false, |
| 19 | + error: null |
| 20 | + }; |
| 21 | + } |
| 22 | + |
| 23 | + handleFormSubmit = e => { |
| 24 | + e.preventDefault(); |
| 25 | + axios({ |
| 26 | + method: "post", |
| 27 | + url: `${process.env.REACT_APP_API}`, |
| 28 | + headers: { "content-type": "application/json" }, |
| 29 | + data: this.state |
| 30 | + }) |
| 31 | + .then(result => { |
| 32 | + this.setState({ |
| 33 | + mailSent: result.data.sent |
| 34 | + }); |
| 35 | + console.log(this.state); |
| 36 | + }) |
| 37 | + .catch(error => this.setState({ error: error.message })); |
| 38 | + }; |
| 39 | + |
| 40 | + render() { |
| 41 | + const { title, successMessage, errorMessage, fields } = this.props.config; |
| 42 | + return ( |
| 43 | + <div className="App"> |
| 44 | + <h2>{title}</h2> |
| 45 | + <div> |
| 46 | + <form action="#"> |
| 47 | + {fields && |
| 48 | + fields.map(fields => { |
| 49 | + return ( |
| 50 | + <React.Fragment> |
| 51 | + {fields.type !== "textarea" ? ( |
| 52 | + <React.Fragment> |
| 53 | + <label>{fields.label}</label> |
| 54 | + <input |
| 55 | + type={fields.type} |
| 56 | + className={fields.klassName} |
| 57 | + placeholder={fields.placeholder} |
| 58 | + value={this.state.fname} |
| 59 | + onChange={e => this.setState({ fname: e.target.value })} |
| 60 | + /> |
| 61 | + </React.Fragment> |
| 62 | + ) : ( |
| 63 | + <React.Fragment> |
| 64 | + <label>{fields.label}</label> |
| 65 | + <textarea |
| 66 | + className={fields.klassName} |
| 67 | + placeholder={fields.placeholder} |
| 68 | + onChange={e => this.setState({ message: e.target.value })} |
| 69 | + value={this.state.message} |
| 70 | + /> |
| 71 | + </React.Fragment> |
| 72 | + )} |
| 73 | + </React.Fragment> |
| 74 | + ); |
| 75 | + })} |
| 76 | + <input type="submit" onClick={e => this.handleFormSubmit(e)} value="Submit" /> |
| 77 | + <div> |
| 78 | + {this.state.mailSent && <div className="sucsess">{successMessage}</div>} |
| 79 | + {this.state.error && <div className="error">{errorMessage}</div>} |
| 80 | + </div> |
| 81 | + </form> |
| 82 | + </div> |
| 83 | + </div> |
| 84 | + ); |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +export default Form; |
| 89 | +//propTypes for the component |
| 90 | +Form.propTypes = { |
| 91 | + config: PropTypes.object.isRequired |
| 92 | +}; |
0 commit comments