I need to dynamically generate multiple divs with input-field in it, so the user can add values in it. By clicking the button user can create as many divs with input-field as he needs By typing values total amount must be calculated in real-time.
My problem is how to get all input values into one array so I could calculate the total. I just need any kind of example how to get those values in one array.
*Note I use functional components.
const ReceiptDetails = () => {
const [isOpen, setIsOpen] = useState(false);
const [selectedOption, setSelectedOption] = useState(null);
const [expenseList, setExpenseList] = useState([]);
const [expenseTotal, setExpenseTotal] = useState(0);
const options = ['Food', 'Entertaiment', 'Houseware'];
const onOptionClicked = (option) => {
setSelectedOption(option);
setIsOpen(false);
};
const formHandler = (e) => {
e.preventDefault();
if (selectedOption !== null) {
setExpenseList(
expenseList.concat(
<ExpenseDetails key={expenseList.length} calcTotal={calcTotal} />
)
);
}
return;
};
return (
<Container>
<Form onSubmit={formHandler}>
<div>
<DropDownHeader onClick={() => setIsOpen(!isOpen)} required>
{selectedOption || 'Select'}
<span className='arrow-head'>⌄</span>
</DropDownHeader>
{isOpen && (
<div>
<DropDownList>
{options.map((option, indx) => (
<ListItem
onClick={() => onOptionClicked(option)}
value={option}
key={indx}
>
{option}
</ListItem>
))}
</DropDownList>
</div>
)}
</div>
<Button type='secondary'>Add expense</Button>
</Form>
{expenseList}
{expenseList.length !== 0 && (
<ExpenseTotal>Total {expenseTotal}</ExpenseTotal>
)}
</Container>
);
};
export default ReceiptDetails;
const ExpenseDetails = () => {
const [expense, setExpense] = useState(0);
return (
<DetailsContainer>
<div className='first'>
<FirstInput type='text' placeholder='Expense name' />
<SecondInput
type='number'
placeholder='€0.00'
value={expense}
onChange={(e) => setExpense(e.target.value)}
/>
</div>
</DetailsContainer>
);
};
export default ExpenseDetails;
CodePudding user response:
how about you use a context? That will allow you to keep and share your state between the components. I'd do something like here. Keep the array of expenses at the context level and the state of the form. From that, you can get the values and display them in the child components.
But it would be best to read the documentation first ;)