Created
March 5, 2021 15:11
-
-
Save MiguelSavignano/41782fc62562478b66e429bfa0f94681 to your computer and use it in GitHub Desktop.
React - Nested Form
This file contains 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, { 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> | |
| |
<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