Dev Helpers
← Back

Select the reading nearest a target

Select the reading nearest a target. Render the transformed entries in a reusable React component.

Open this example in the interactive library

Live preview

Source code

// CollectionView.tsx
export default function CollectionView() {
  const rows = [
    { site: "N", hour: 8, value: 12 },
    { site: "S", hour: 8, value: 17 },
    { site: "N", hour: 9, value: 15 },
    { site: "S", hour: 9, value: 14 },
  ];
  const result = rows.toSorted(
    (a, b) => Math.abs(a.value - 16) - Math.abs(b.value - 16),
  )[0];
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Select the reading nearest a target"}</h2>
      {entries.length ? (
        <dl>
          {entries.map(([key, value]) => (
            <div key={key}>
              <dt>{key}</dt>
              <dd>
                {typeof value === "string" ? value : JSON.stringify(value)}
              </dd>
            </div>
          ))}
        </dl>
      ) : (
        <p>No matching entries.</p>
      )}
    </section>
  );
}