Child to Parent | React
We have 3 pages from top to bottom:
-App
-NewExpense
-ExpenseForm
We try to sent props from ExpenseForm to App.
ExpenseForm
const submitHandler = (event) => { event.preventDefault();
const expenseData =
{
title: enteredTitle,
amount: enteredAmount,
date: new Date(enteredDate),
};
props.onSaveExpenseData(expenseData);
};
We take inputs from user and we get all datas in expenseData
We sent expenseData with onSaveExpenseData adding props tag.
Where to sent ? To the NewExpense !
NewExpense
Really we sent the onSaveExpenseData props from here and ExpenseForm fills this props with expenseData and it sents to NewExpense
return (
<ExpenseForm onSaveExpenseData={saveExpenseDataHandler} />
);
Illustration time
const saveExpenseDataHandler = (enteredExpenseData) => {
const expenseData = {
…enteredExpenseData,
id: Math.random().toString()
};
props.onAddExpense(expenseData);
};
NewExpense takes this datas as the parameter in saveExpenseDataHandler function and creates expenseData and it sents with onExpenseData adding props tag.
App
Really we sent onAddExpense props from here and NewExpense fills this props with expenseData and it sents to App.
return (
<NewExpense onAddExpense={addExpenseHandler} />
);
const addExpenseHandler = expense => {
console.log(expense);
}
App page takes this data as parameter (expense) in addExpenseHandler function.