Skip to content

Commit 17f1a65

Browse files
committed
better use effects
1 parent 46f6353 commit 17f1a65

File tree

3 files changed

+23
-13
lines changed

3 files changed

+23
-13
lines changed

src/components/alert/index.tsx renamed to src/components/alert.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
InfoCircledIcon,
66
} from '@radix-ui/react-icons';
77

8-
import {Callout} from '../callout';
8+
import {Callout} from './callout';
99

1010
type AlertProps = {
1111
children?: ReactNode;

src/components/callout/index.tsx

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import {ForwardRefExoticComponent, MouseEventHandler, ReactNode} from 'react';
1+
import {
2+
ForwardRefExoticComponent,
3+
MouseEventHandler,
4+
ReactNode,
5+
useCallback,
6+
} from 'react';
27

38
// explicitly not usig CSS modules here
49
// because there's some prerendered content that depends on these exact class names
@@ -24,6 +29,19 @@ function Header({
2429
id?: string;
2530
onClick?: MouseEventHandler;
2631
}) {
32+
// We want to avoid actually triggering the link
33+
const preventDefaultOnClick = useCallback(
34+
(event: React.MouseEvent) => {
35+
if (!onClick) {
36+
return;
37+
}
38+
39+
event.preventDefault();
40+
onClick(event);
41+
},
42+
[onClick]
43+
);
44+
2745
if (!id) {
2846
return (
2947
<h5
@@ -36,17 +54,9 @@ function Header({
3654
);
3755
}
3856

39-
// We want to avoid actually triggering the link
40-
const wrappedOnClick = onClick
41-
? (event: React.MouseEvent) => {
42-
event.preventDefault();
43-
onClick(event);
44-
}
45-
: undefined;
46-
4757
return (
4858
<h5 className="callout-header" id={id}>
49-
<a href={'#' + id} onClick={wrappedOnClick}>
59+
<a href={'#' + id} onClick={preventDefaultOnClick}>
5060
{title}
5161
</a>
5262
</h5>

src/components/expandable.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@ function slugify(str: string) {
2222
export function Expandable({title, level, children, permalink}: Props) {
2323
const id = permalink ? slugify(title) : undefined;
2424

25-
const defaultIsExpanded = id && window.location.hash === `#${id}`;
26-
const [isExpanded, setIsExpanded] = useState(defaultIsExpanded);
25+
const [isExpanded, setIsExpanded] = useState(false);
2726

2827
// Ensure we scroll to the element if the URL hash matches
2928
useEffect(() => {
3029
if (id && window.location.hash === `#${id}`) {
3130
document.querySelector(`#${id}`)?.scrollIntoView();
31+
setIsExpanded(true);
3232
}
3333

3434
// When the hash changes (e.g. when the back/forward browser buttons are used),

0 commit comments

Comments
 (0)