-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy path_dynamic-code.tsx
More file actions
43 lines (41 loc) · 1.17 KB
/
_dynamic-code.tsx
File metadata and controls
43 lines (41 loc) · 1.17 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
'use client'
import { Button } from 'nextra/components'
import type { FC, ReactNode } from 'react'
import { useEffect, useRef } from 'react'
export const DynamicCode: FC<{ children: ReactNode }> = ({ children }) => {
const ref = useRef<HTMLDivElement>(null!)
const tokenRef = useRef<HTMLSpanElement>(undefined)
// Find the corresponding token from the DOM
useEffect(() => {
tokenRef.current = [
...ref.current.querySelectorAll<HTMLSpanElement>('code > span > span')
].find(el => el.textContent === '1')
}, [])
return (
<>
<div ref={ref} className="mt-6">
{children}
</div>
<div className="mt-3 flex justify-center gap-3 text-sm">
<Button
variant="outline"
onClick={() => {
const token = tokenRef.current!
const prev = token.textContent
token.textContent = String((+prev || 0) + 1)
}}
>
Increase the number
</Button>
<Button
variant="outline"
onClick={() => {
tokenRef.current!.textContent = '1 + 1'
}}
>
Change to `1 + 1`
</Button>
</div>
</>
)
}