Rules Hub
Coding Rules Library
Extract data preparation from JSX loops
Avoid performing complex data formatting or object creation inside JSX map callbacks; extract this logic into a separate helper function or prepare the data beforehand.
Bad example
| 1 | return ( |
| 2 | <tbody> |
| 3 | {invoices.map((invoice) => { |
| 4 | // Bad: Complex logic and formatting inside the render loop |
| 5 | const date = new Date(invoice.date).toLocaleDateString('no-NO'); |
| 6 | const amount = invoice.amount.toFixed(2).replace('.', ','); |
| 7 | const status = invoice.isPaid ? 'Betalt' : 'Ubetalt'; |
| 8 | |
| 9 | return ( |
| 10 | <tr key={invoice.id}> |
| 11 | <td>{date}</td> |
| 12 | <td>{amount}</td> |
| 13 | <td>{status}</td> |
| 14 | </tr> |
| 15 | ); |
| 16 | })} |
| 17 | </tbody> |
| 18 | ); |
Explanation (EN)
Defining variables and performing formatting logic inside the JSX `map` callback clutters the render method. It mixes data transformation with UI structure, making the component harder to read and the logic harder to test independently.
Objašnjenje (HR)
Definiranje varijabli i izvođenje logike formatiranja unutar JSX `map` callbacka zatrpava render metodu. Miješa se transformacija podataka s UI strukturom, što otežava čitanje komponente i nezavisno testiranje logike.
Good example
| 1 | // Logic extracted to a pure helper function |
| 2 | const getInvoiceRow = (invoice: Invoice) => ({ |
| 3 | id: invoice.id, |
| 4 | date: new Date(invoice.date).toLocaleDateString('no-NO'), |
| 5 | amount: invoice.amount.toFixed(2).replace('.', ','), |
| 6 | status: invoice.isPaid ? 'Betalt' : 'Ubetalt', |
| 7 | }); |
| 8 |
|
| 9 | export const InvoiceTable = ({ invoices }: Props) => { |
| 10 | // Data prepared before the return statement |
| 11 | const rows = invoices.map(getInvoiceRow); |
| 12 |
|
| 13 | return ( |
| 14 | <tbody> |
| 15 | {rows.map((row) => ( |
| 16 | <tr key={row.id}> |
| 17 | <td>{row.date}</td> |
| 18 | <td>{row.amount}</td> |
| 19 | <td>{row.status}</td> |
| 20 | </tr> |
| 21 | ))} |
| 22 | </tbody> |
| 23 | ); |
| 24 | }; |
Explanation (EN)
The data transformation logic is extracted into a dedicated helper function (`getInvoiceRow`). The JSX block is now purely declarative, rendering pre-calculated data, which improves readability and separation of concerns.
Objašnjenje (HR)
Logika transformacije podataka izdvojena je u zasebnu pomoćnu funkciju (`getInvoiceRow`). JSX blok je sada čisto deklarativan i prikazuje unaprijed izračunate podatke, što poboljšava čitljivost i odvajanje odgovornosti.