skip to Main Content
 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


  1. The problem exists on Input component, you need to make arr as state variable using useState.

    const [arr, setArr] = useState([])

    And instead of arr.push, setArr(arr => [...arr, {expense, amount}])

    Login or Signup to reply.
  2. 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}]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search