summaryrefslogtreecommitdiff
path: root/examples/blog/src/components/LikeButton.tsx
blob: 23d8518de9ece541836db8d63710efab88b713b1 (plain) (blame)
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
import { useState } from 'preact/hooks';

interface Props {
	pageUrl: string;
}

export default function LikeButton({ pageUrl }: Props) {
	const persistedLike = localStorage.getItem(`liked-${pageUrl}`);
	const [liked, setLiked] = useState(persistedLike ? JSON.parse(persistedLike) : false);

	function toggleLike() {
		const toggled = !liked;
		setLiked(toggled);
		// preserve your likes as you navigate the site
		localStorage.setItem(`liked-${pageUrl}`, JSON.stringify(toggled));
	}

	return (
		<button onClick={toggleLike}>
			<svg
				xmlns="http://www.w3.org/2000/svg"
				xmlnsXlink="http://www.w3.org/1999/xlink"
				width="1em"
				height="1em"
				viewBox="0 0 24 24"
			>
				{/* fill the heart when liked ♥ */}
				<path
					fill={liked ? 'red' : '#ccc'}
					d="m12 21.35l-1.45-1.32C5.4 15.36 2 12.27 2 8.5C2 5.41 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.08C13.09 3.81 14.76 3 16.5 3C19.58 3 22 5.41 22 8.5c0 3.77-3.4 6.86-8.55 11.53L12 21.35Z"
				></path>
			</svg>
		</button>
	);
}