Last active
January 2, 2023 16:48
-
-
Save Orbis25/bc5c81b4255ec682b2f7a6175cb21e23 to your computer and use it in GitHub Desktop.
Generic table in reactjs + typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage