This repository was archived by the owner on Apr 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathindex.tsx
More file actions
80 lines (70 loc) · 2.26 KB
/
index.tsx
File metadata and controls
80 lines (70 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React from 'react';
import { renderToString } from 'react-dom/server';
const mutateChildren = (
children: JSX.Element[] | JSX.Element,
oldTag: string,
newTag: string
): string => {
if (Array.isArray(children)) {
return children
.map(child => renderToString(child).replace(oldTag, newTag))
.join('');
}
return mutateChildren([children], oldTag, newTag);
};
const surroundChildren = (children: JSX.Element[] | JSX.Element, tag: string) =>
`<${tag}>${mutateChildren(children, '<th', '<td')}</${tag}>`;
// This component exists to normalise HTML tables following the format
// That always a <thead> and a <tbody> are mandatory
// It also fixes up Tables that have swapped th's and td's
const Table = ({ children }: React.PropsWithChildren): JSX.Element | null => {
if (!children || !Array.isArray(children)) {
return null;
}
const filteredChildren = children.filter(c => typeof c === 'object');
if (filteredChildren.length === 0) {
return null;
}
if (filteredChildren.length === 1) {
return (
<table>
<tbody
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: mutateChildren(
filteredChildren[0].props.children,
'<th',
'<td'
),
}}
/>
</table>
);
}
const isFirstElementHeader = filteredChildren[0].props.mdxType === 'thead';
const isSecondElementBody = filteredChildren[1].props.mdxType === 'tbody';
return (
<table>
<thead
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: !isFirstElementHeader
? mutateChildren(filteredChildren[0].props.children, '<td', '<th')
: renderToString(filteredChildren[0].props.children as JSX.Element),
}}
/>
<tbody
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: !isSecondElementBody
? filteredChildren
.slice(1)
.map(item => surroundChildren(item.props.children, 'tr'))
.join('')
: renderToString(filteredChildren[1].props.children as JSX.Element),
}}
/>
</table>
);
};
export default Table;