I am new to React and for my first project I'm trying to build an expense-tracker, by Traversy Media on YT.
I've thought to expand project a little bit by adding a date component to it. My current output looks as follows: Image 1
And I want to look it as such: Image 2 (I hard-coded this output)
Basically I want Date component to only re-render if and only if no other component with same date exists. If component with same date exists the output should fall under it. I am confused with both logic of the problem and conditional rendering itself.
Here's what I've coded up until now:
const TransactionList = () => {
const {transactions} = useContext(GlobalContext)
return(
<div>
<h3>History</h3>
<ul className='list'>
{transactions.map(transaction => (
<Transaction key={transaction.id} transaction={transaction}/>
))}
</ul>
<div>
)
}
In above code transactions is an array which will be an initial-state of Global Context.
Code for component Transaction is as follows:
export const Transaction = ({transaction}) => {
const { deleteTransaction } = useContext(GlobalContext)
const sign = transaction.amount > 0 ? '+' : '-'
return (
<div>
<ExpenseDate date={transaction.date} />
<li className={transaction.amount > 0 ? 'plus' : 'minus' }>
{transaction.text} <span>{sign}₹{Math.abs(transaction.amount)}</span>
</li>
</div>
)
}
And code for ExpenseDate is as follows:
function ExpenseDate(props){
const month = props.date.toLocaleString('en-US', {month: 'long'})
const year = props.date.getFullYear();
const day = props.date.getDate();
return (
<span className="expense-date">
<span >{day}</span> <span >{month}</span> <span >{year}</span>
</span>
)
}
My guess is the first step for conditional rendering will be to remove ExpenseDate as child of tag. The help will be very much appreciated. Thank You :))
Few approaches you can consider doing in this case.
change the structure of transactions to be grouped by date and have another component inside TransactionList
which can render the group of ExpenseDate
and Transaction
Another approach is, if dates are sorted by default, then we can check if previous date is same as current date and hide the ExpenseDate
component. https://codesandbox.io/s/tender-yonath-dy1pli-dy1pli?file=/src/components/TransactionList.js
First approach will be cleaner as it clearly defines the data in the shape we need