bhylu.com

Advertisements

React Array Methods

Use filter and map for separate decisions: which records belong and what each record becomes.

How it works

A lending desk may receive more records than it should show. filter keeps records that satisfy a predicate. map transforms each retained record into another value, including JSX. Neither method needs to mutate the original array. Keeping these decisions readable makes empty results easier to explain later. The example selects available items and turns each into a list entry using an ID that belongs to the item.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

const items = [
  { id: 'stool', name: 'Folding stool', available: true },
  { id: 'lamp', name: 'Desk lamp', available: false },
  { id: 'basket', name: 'Market basket', available: true },
];
function App() {
  const ready = items.filter((item) => item.available);
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <ul>
        {ready.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <output>{ready.length} items ready</output>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

The stool and basket appear; the unavailable lamp does not. The count is two.

The predicate returns a boolean and the mapper returns a list element. Both callbacks have clear inputs and no side effects. ready.length comes from the filtered array, avoiding a second count that could disagree with the visible rows. An empty array renders no rows; a later conditional can add a helpful message. The stable keys help React preserve identity when records move.

For API contracts and version differences, use React’s official documentation.

Advertisements