Skip to main content

13.04 Setting Up Js Config For Form

Input.js

Input.js
import React from "react";
import classes from "./Input.module.css";

const input = (props) => {
let inputElement = null;

switch (props.elementType) {
case "input":
inputElement = (
<input
className={classes.InputElement}
{...props.elementConfig}
value={props.value}
/>
);
break;
case "textarea":
inputElement = (
<textarea
className={classes.InputElement}
{...props.elementConfig}
value={props.value}
/>
);
break;
default:
inputElement = (
<input
className={classes.InputElement}
{...props.elementConfig}
value={props.value}
/>
);
}
return (
<div className={classes.Input}>
<label className={classes.Label}>{props.label}</label>
{inputElement}
</div>
);
};

export default input;

ContactData.js

ContactData.js
import React, { Component } from "react";
import axios from "../../../axios-orders";
import Button from "../../../components/UI/Button/Button";
import Input from "../../../components/UI/Input/Input";
import Spinner from "../../../components/UI/Spinner/Spinner";
import classes from "./ContactData.module.css";

class ContactData extends Component {
state = {
orderForm: {
name: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Your Name",
},
value: "",
},
street: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Street",
},
value: "",
},
zipCode: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "ZIP Code",
},
value: "",
},
country: {
elementType: "input",
elementConfig: {
type: "text",
placeholder: "Country",
},
value: "",
},
email: {
elementType: "input",
elementConfig: {
type: "email",
placeholder: "Your e-mail",
},
value: "",
},
deliveryMethod: {
elementType: "select",
elementConfig: {
options: [
{ value: "fastest", displayValue: "Fastest" },
{ value: "cheapest", displayValue: "Cheapest" },
],
},
value: "",
},
},
loading: false,
};

orderHandler = (event) => {
event.preventDefault();
this.setState({ loading: true });
const order = {
ingredients: this.props.ingredients,
price: this.props.price,
};
axios
.post("/orders.json", order)
.then((response) => {
this.setState({ loading: false });
this.props.history.push("/");
})
.catch((error) => {
this.setState({ loading: false });
});
};
render() {
let form = (
<form>
<Input elementType="..." elementConfig="..." value="..." />
<Input
inputtype="input"
type="text"
name="email"
placeholder="Your Mail"
/>
<Input
inputtype="input"
type="text"
name="street"
placeholder="Street"
/>
<Input
inputtype="input"
type="text"
name="postal"
placeholder="Postal Code"
/>
<Button btnType="Success" clicked={this.orderHandler}>
ORDER
</Button>
</form>
);
if (this.state.loading) {
form = <Spinner />;
}
return (
<div className={classes.ContactData}>
<h4>Enter your Contact Data</h4>
{form}
</div>
);
}
}
export default ContactData;