Sobes.tech
Middle

Practical task: implement a table component in React + TypeScript with parameterization through props (data, columns, onRowClick handler), which shows an alert with the record ID on row click.

sobes.tech AI

Answer from AI

tsx import React from 'react';

Type Column<T> = { key: keyof T; label: string; };

Type TableProps<T extends { id: string | number }> = { data: T[]; columns: Column<T>[]; onRowClick: (id: T['id']) => void; };

function Table<T extends { id: string | number }>({ data, columns, onRowClick }: TableProps<T>) { return ( <table> <thead> <tr> {columns.map(col => ( <th key={String(col.key)}>{col.label}</th> ))} </tr> </thead> <tbody> {data.map(row => ( <tr key={String(row.id)} onClick={() => onRowClick(row.id)} style={{ cursor: 'pointer' }}> {columns.map(col => ( <td key={String(col.key)}>{String(row[col.key])}</td> ))} </tr> ))} </tbody> </table> ); }

// Example usage:

// type User = { id: number; name: string; age: number }; // const users: User[] = [ // { id: 1, name: 'Ivan', age: 30 }, // { id: 2, name: 'Maria', age: 25 }, // ]; // const columns = [ // { key: 'name', label: 'Name' }, // { key: 'age', label: 'Age' }, // ]; // // <Table // data={users} // columns={columns} // onRowClick={(id) => alert(You clicked on record with id: ${id})} // />

Practical task: implement a table component in React… - sobes.tech