import History from "./History";
import { useState } from "react";
const Input = function () {
const arr = [];
const [expense, setExpense] = useState("");
const [amount, setAmount] = useState("");
const [state, setState] = useState(false);
const expenseChangeHandler = function (e) {
setExpense(e.target.value);
};
const amountChangeHandler = function (e) {
setAmount(e.target.value);
};
const clickHandler = function () {
setState(true);
arr.push({
expense: expense,
amount: amount,
});
};
return (
<div>
<input
value={expense}
onChange={expenseChangeHandler}
></input>
<input
value={amount}
onChange={amountChangeHandler}
></input>
<button onClick={clickHandler}>Add</button>
{state && <History arr={arr}></History>}
</div>
);
};
export default Input;
Basically whats important to note here is that I am passing in the arr array as a prop for the History component.
import "./History.css";
const History = function (props) {
const arr = props.arr;
const newArr = arr.map((el) => <p>{el.expense}</p>);
return (
<div className="div1">
<h2>History</h2>
<div>{newArr}</div>
</div>
);
};
export default History;
When the button in the parent component, Input, is clicked all it renders is ‘History’, from the h2 tag but I also want it to render the expense from the arr array. Any help?
2
Answers
The problem exists on Input component, you need to make
arr
as state variable usinguseState
.const [arr, setArr] = useState([])
And instead of arr.push,
setArr(arr => [...arr, {expense, amount}])
I have solved the issue, here is the link https://codesandbox.io/s/peaceful-williamson-g8r2vl?file=/src/App.js
you need a have arr as state variable and update it […arr,{newarritem}]