Home > Blockchain >  ReactJS, passing data via "props" not working
ReactJS, passing data via "props" not working

Time:12-21

I am using Node v16. I tried to pass some values via props, but nothing seems to appear. The names seem to match and no errors in the console too. I have shared the sample code below. None of the values are being displayed on the browser, just the empty HTML and CSS.

ExpenseItem.js

import './ExpenseItem.css'

function ExpenseItem(props) {

  const expenseDate=new Date(2021,2,28);
  const expenseTitle='Car Insurance';
  const expenseAmount = 294.67;
  
  return (
    <div className="expense-item">
      <div>{props.date} </div>
      <div className="expense-item__description">
        <h2>{props.title}</h2>
        <div className="expense-item__price">${props.amount}</div>
      </div>
    </div>
  );
}

export default ExpenseItem;

App.js

import ExpenseItem from "./components/ExpenseItem";

function App() {
  const expenses = [
    {
      id: "e1",
      title: "Toilet Paper",
      amount: 94.12,
      date: new Date(2020, 7, 14),
    },
    { id: "e2", title: "New TV", amount: 799.49, date: new Date(2021, 2, 12) },
    {
      id: "e3",
      title: "Car Insurance",
      amount: 294.67,
      date: new Date(2021, 2, 28),
    },
    {
      id: "e4",
      title: "New Desk (Wooden)",
      amount: 450,
      date: new Date(2021, 5, 12),
    },
  ];

  return (
    <div>
      <h2>Let's get started</h2>

      <ExpenseItem>
        title={expenses[0].title}
        amount={expenses[0].amount}
        date={expenses[0].date}
      </ExpenseItem>

      <ExpenseItem>
        title={expenses[1].title}
        amount={expenses[1].amount}
        date={expenses[1].date}
      </ExpenseItem>

      <ExpenseItem>
        title={expenses[2].title}
        amount={expenses[2].amount}
        date={expenses[2].date}
      </ExpenseItem>
      
      <ExpenseItem>
        title={expenses[3].title}
        amount={expenses[3].amount}
        date={expenses[3].date}
      </ExpenseItem>
    </div>
  );
}

export default App;

None of the values are being displayed on the browser, just the empty HTML and CSS.

CodePudding user response:

The props should place inside element tag.

<ExpenseItem title={expenses[0].title}></ExpenseItem>

CodePudding user response:

Change,

<ExpenseItem>
   title={expenses[3].title}
   amount={expenses[3].amount}
   date={expenses[3].date}
 </ExpenseItem>

to

<ExpenseItem
   title={expenses[3].title}
   amount={expenses[3].amount}
   date={expenses[3].date}
/>

CodePudding user response:

Those are not props, those are children, also, that repeated data could be improved with a .map call to your data.

  return (
    <div>
      <h2>Let's get started</h2>

      { expenses.map(expense => (
        <ExpenseItem
          key={expense.id}
          title={expense.title}
          amount={expense.amount}
          date={expense.date}
        />
      )) }
    </div>
  );
  • Related