Skip to content

Instantly share code, notes, and snippets.

@MiguelSavignano
Created March 5, 2021 15:11
Show Gist options
  • Save MiguelSavignano/41782fc62562478b66e429bfa0f94681 to your computer and use it in GitHub Desktop.
Save MiguelSavignano/41782fc62562478b66e429bfa0f94681 to your computer and use it in GitHub Desktop.
React - Nested Form
import React, { useState } from 'react';
import { Alert, Button, Col, Form, Modal } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
const TestPage = () => {
const defaultIngredient = { name: '', amount: '' };
const [ingredients, setIngredients] = useState([defaultIngredient]);
function addIngredient() {
setIngredients([...ingredients, defaultIngredient]);
}
const onChangeIngredient = (index: number) => ({ target: { value, name } }: any) => {
const newIngredients = ingredients.map(
(ingredient, _index) => (_index == index ? { ...ingredient, [name]: value } : ingredient)
);
setIngredients(newIngredients);
};
console.log(ingredients);
function onSubmit(event: any) {
event.preventDefault();
console.log('Save', { ingredients });
}
return (
<div className="wrapper">
<h1>Prepare your Recipe!!</h1>
<Form onSubmit={onSubmit}>
<Button onClick={addIngredient}>Add +</Button>
&nbsp; &nbsp;
<Button type="submit"> Save</Button>
{ingredients.map((_: any, index: number) => (
<Form.Row key={index}>
<Form.Group as={Col} controlId="formGridName">
<Form.Label>Name</Form.Label>
<Form.Control
size="lg"
autoComplete="off"
type="text"
name="name"
placeholder=""
onChange={onChangeIngredient(index)}
/>
<Form.Label>Amount</Form.Label>
<Form.Control
size="lg"
autoComplete="off"
type="string"
name="amount"
onChange={onChangeIngredient(index)}
placeholder=""
/>
</Form.Group>
</Form.Row>
))}
</Form>
</div>
);
};
export default TestPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment