Skip to content

Instantly share code, notes, and snippets.

@Orbis25
Last active January 2, 2023 16:48
Show Gist options
  • Save Orbis25/bc5c81b4255ec682b2f7a6175cb21e23 to your computer and use it in GitHub Desktop.
Save Orbis25/bc5c81b4255ec682b2f7a6175cb21e23 to your computer and use it in GitHub Desktop.
Generic table in reactjs + typescript
import { Table } from "react-bootstrap";
import "./styles.css";
type Props = {
headers: string[];
data: any[];
showId?: boolean;
handleClick: (id: string | undefined) => void;
};
const TableComponent: React.FC<Props> = ({
showId = false,
data,
headers,
handleClick,
}) => {
//event or methods
const getHeaders = () => {
if (!showId) return headers.filter((x) => x.toLowerCase() !== "id");
return headers;
};
/**
* Map o populate the data
* @returns string[][]
*/
const getDataMapped = () => {
const results = data.map((x) => {
return Object.values(x);
});
return results as string[][];
};
//conditional-components
const _renderContent = (header: string, value: string[], index: number) => {
const item = value[index];
if (header.toLowerCase() === "estatus") {
return <span className={`status-${item}`}>{item}</span>;
} else return <span>{item}</span>;
};
const _renderHeaders = () => {
return getHeaders().map((value: string) => {
return <th key={value}>{value}</th>;
});
};
return (
<>
<Table hover size="sm">
<thead className="tablet-head">
<tr>{_renderHeaders()}</tr>
</thead>
<tbody>
{getDataMapped().map((value, key) => (
<tr className="table-item" key={key}>
{headers.map((header: string, index) => {
if (header.toLowerCase() === "id" && !showId) {
return (
<td style={{ display: "none" }} key={index}>
{_renderContent(header, value, index)}
</td>
);
} else {
return (
<td
onClick={() => {
handleClick(data[key].id);
}}
key={index}
>
{_renderContent(header, value, index)}
</td>
);
}
})}
</tr>
))}
</tbody>
</Table>
</>
);
};
export default TableComponent;
@Orbis25
Copy link
Author

Orbis25 commented Jun 25, 2021

Usage

code2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment