Ad

React Looping Hooks To Display In Other Hook

- 1 answer

I'm working on a react Web App, and I'm trying to loop a list of objects and output the content to another hook, see below for details.

the issue that I'm facing is when I loop the object, I just get one result.

Object.keys(transactions).forEach((key, index) =>
    {output =  <TransactionsItem name={transactions[key].lable} />}
)

When I try to concatenate, it doesn't work.

Object.keys(transactions).forEach((key, index) =>
    {output = output + <TransactionsItem name={transactions[key].lable} />}
)

How can i concatenate ?

Full info if needed

transactionsList hook

const Transactions = () =>{

  var [user, setUser] = useContext(UserContext);

  function TransactionList(props){
    var output
    transactions = props.user.transactions
    Object.keys(transactions).forEach((key, index) =>
      {output =  <TransactionsItem name={transactions[key].lable} />}
    )
    return(output);
  }

  return(
    <div>
      <Menu />
          <TransactionList user={user} />
        </Grid>
      </div>
    </div>

  )
}

TransactionList

const TransactionsItem = (props) => {
  return(
    <div>{props.name}</div>
  );
}

Object

{
-LqaBL5jD3ktq_duQNH2: {amount: 5, date: "07/10/2019, 23:28:37", lable: "coffee"},
-LqaBLZlT_zGjr9pngWE: {amount: 5, date: "07/10/2019, 23:28:39", lable: "coffee"},
-LqaBLqKtdbp15PGdwDs: {amount: 10, date: "07/10/2019, 23:28:40", lable: "Ride"},
-LqaBM9QiHwUtmNgHN5P: {amount: 10, date: "07/10/2019, 23:28:41", lable: "Lunch"},
-LqfCNGS-4fRbgTZFnn6: {amount: 10, date: "08/10/2019, 22:51:14", lable: "Ride"},
-LqfCONTvk5p0MfK2tGc: {amount: 10, date: "08/10/2019, 22:51:18", lable: "Ride"},
-LqfCOjq1lO9auOnka1S: {amount: 10, date: "08/10/2019, 22:51:20", lable: "Ride"},
}
Ad

Answer

use javascript map instead of forEach,

function TransactionList(props){
    var output
    transactions = props.user.transactions
    output = Object.keys(transactions).map((key, index) => <TransactionsItem name={transactions[key].lable} />)
    return(output);
  }

Hope the above will work.

Ad
source: stackoverflow.com
Ad