Add a like button to Next.js and React
The button is a custom element, so React renders it like any tag. Load the script once for the app and put the element in your post page.
Before you start: get a key
- Sign in with GitHub on the dashboard and add your site.
-
Create a button. In its allowed origins, list every address your site
is served from, one per line and without a path, such as
https://example.com. Add the address you preview on locally too, exactly as the browser shows it. A page on an origin that is not listed cannot load the button, so nobody else can use your key. -
Copy the key. It starts with
pk_. Below, it stands in aspk_YOUR_BUTTON_KEY.
1. Load the script once
In the App Router, add it to app/layout.tsx:
import Script from 'next/script';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Script src="https://appreciate-button.com/widget.js" strategy="afterInteractive" />
</body>
</html>
);
}
With the Pages Router, put the same Script in pages/_app.tsx. In
a React app without Next.js, such as Vite, add a plain
<script src="…/widget.js" async></script> to
index.html.
2. Render the element in the post page
<article>
{/* the post */}
<appreciate-button data-key="pk_YOUR_BUTTON_KEY" />
</article>
With TypeScript, declare the element once, for example in
appreciate-button.d.ts:
import type { DetailedHTMLProps, HTMLAttributes } from 'react';
declare module 'react' {
namespace JSX {
interface IntrinsicElements {
'appreciate-button': DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>;
}
}
}
Things to know
- Client-side navigation needs nothing extra: the button notices the new address and loads that page's count.
-
afterInteractiveloads the script after hydration, so the button's own attributes never differ from what the server rendered. -
Listen for
appreciate:changeand the other events on the element to react to clicks in your own code. - Allow
http://localhost:3000to try it withnext dev.