Skip to content

Commit e5f8fef

Browse files
Fix Heading Link Error (#555)
* fix link error * rm .idea folder
1 parent 5e53b15 commit e5f8fef

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

src/components/Markdown.tsx

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,28 +17,45 @@ import { useMarkdownHeadings } from '~/components/MarkdownHeadingContext'
1717
import { renderMarkdown } from '~/utils/markdown'
1818
import { Tabs } from '~/components/Tabs'
1919

20+
type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
21+
2022
const CustomHeading = ({
2123
Comp,
2224
id,
25+
children,
2326
...props
2427
}: HTMLProps<HTMLHeadingElement> & {
25-
Comp: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
28+
Comp: HeadingLevel
2629
}) => {
30+
// Convert children to array and strip any inner anchor (native 'a' or MarkdownLink)
31+
const childrenArray = React.Children.toArray(children)
32+
const sanitizedChildren = childrenArray.map((child) => {
33+
if (React.isValidElement(child) && (child.type === 'a' || child.type === MarkdownLink)) {
34+
// replace anchor child with its own children so outer anchor remains the only link
35+
return child.props.children ?? null
36+
}
37+
return child
38+
})
39+
40+
const heading = (
41+
<Comp id={id} {...props}>
42+
{sanitizedChildren}
43+
</Comp>
44+
)
45+
2746
if (id) {
2847
return (
29-
<a
30-
href={`#${id}`}
31-
className={`anchor-heading *:scroll-my-20 *:lg:scroll-my-4`}
32-
>
33-
<Comp id={id} {...props} />
48+
<a href={`#${id}`} className={`anchor-heading *:scroll-my-20 *:lg:scroll-my-4`}>
49+
{heading}
3450
</a>
3551
)
3652
}
37-
return <Comp {...props} />
53+
54+
return heading
3855
}
3956

4057
const makeHeading =
41-
(type: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6') =>
58+
(type: HeadingLevel) =>
4259
(props: HTMLProps<HTMLHeadingElement>) =>
4360
(
4461
<CustomHeading

0 commit comments

Comments
 (0)