Skip to content

Commit 7ff4256

Browse files
committed
refactor: anchorme component
1 parent 8e9fed3 commit 7ff4256

1 file changed

Lines changed: 24 additions & 27 deletions

File tree

src/Anchorme.tsx

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -12,36 +12,33 @@ type Props = {
1212
const Anchorme = ({ children, ...rest }: Props) => {
1313
const text = Array.isArray(children) ? children.join('') : children
1414

15-
const parsedText = useMemo(() => {
16-
const matches = anchorme.list(text)
17-
if (matches.length === 0) return text
18-
19-
const elements = []
20-
let lastIndex = 0
21-
matches.forEach((match) => {
22-
// Push text located before matched string
23-
if (match.start > lastIndex) {
24-
elements.push(text.substring(lastIndex, match.start))
25-
}
26-
27-
// Push Link component
28-
elements.push(
29-
<Link {...rest} key={`link-${match.start}`} href={match.string} />,
30-
)
31-
32-
lastIndex = match.end
33-
})
34-
35-
// Push remaining text
36-
if (text.length > lastIndex) {
37-
elements.push(text.substring(lastIndex))
15+
const matches = useMemo(() => anchorme.list(text), [text])
16+
17+
if (matches.length === 0) return <>{text}</>
18+
19+
const elements = []
20+
let lastIndex = 0
21+
matches.forEach((match) => {
22+
// Push text located before matched string
23+
if (match.start > lastIndex) {
24+
elements.push(text.substring(lastIndex, match.start))
3825
}
3926

40-
return elements.length === 1 ? elements[0] : elements
41-
// eslint-disable-next-line react-hooks/exhaustive-deps
42-
}, [text])
27+
// Push Link component
28+
elements.push(
29+
<Link {...rest} key={`link-${match.start}`} href={match.string} />,
30+
)
31+
32+
lastIndex = match.end
33+
})
34+
35+
// Push remaining text
36+
if (text.length > lastIndex) {
37+
elements.push(text.substring(lastIndex))
38+
}
4339

44-
return <>{parsedText}</>
40+
const result = elements.length === 1 ? elements[0] : elements
41+
return <>{result}</>
4542
}
4643

4744
export default React.memo(Anchorme)

0 commit comments

Comments
 (0)