Getting started with the Knock React Native SDK
Get started with the Knock React Native SDK to build in-app notification experiences.
To get started, you will need the following:
- A Knock account
- A public API key for the Knock environment (which you'll use in the
publishableKey
) - An in-app feed channel with a workflow that produces in-app feed messages (optional)
Installation
- Via NPM:
npm install @knocklabs/react-native
- Via Yarn:
yarn add @knocklabs/react-native
💡
Using Expo? Install
@knocklabs/expo
instead to use our Expo SDK.Configuration
To configure the feed you will need:
-
A public API key (found in the Knock dashboard)
-
A user ID and an auth token
💡Auth tokens are strongly recommended for production environments and are required when enhanced security mode is enabled. For more information, see our Security & Authentication documentation. -
If integrating an in-app feed, a feed channel ID (found in the Knock dashboard)
Usage
You can integrate the feed into your app as follows:
1import {
2 KnockProvider,
3 KnockFeedProvider,
4 NotificationFeed,
5} from "@knocklabs/react-native";
6
7const YourAppLayout = () => {
8 return (
9 <KnockProvider apiKey={process.env.KNOCK_PUBLIC_API_KEY} userId={userId}>
10 {/* Optionally, use the KnockFeedProvider to connect an in-app feed */}
11 <KnockFeedProvider feedId={process.env.KNOCK_FEED_ID}>
12 <NotificationFeed
13 onRowTap={(item) => {
14 console.log("Notification tapped:", item);
15 }}
16 />
17 </KnockFeedProvider>
18 </KnockProvider>
19 );
20};
Headless usage
Alternatively, if you don't want to use our components you can render the feed in a headless mode using our hooks:
1import {
2 useAuthenticatedKnockClient,
3 useNotifications,
4 useNotificationStore,
5} from "@knocklabs/react-native";
6
7const YourAppLayout = () => {
8 const knockClient = useAuthenticatedKnockClient(
9 process.env.KNOCK_PUBLIC_API_KEY,
10 currentUser.id,
11 );
12
13 const notificationFeed = useNotifications(
14 knockClient,
15 process.env.KNOCK_FEED_ID,
16 );
17
18 const { metadata } = useNotificationStore(notificationFeed);
19
20 useEffect(() => {
21 notificationFeed.fetch();
22 }, [notificationFeed]);
23
24 return <Text>Total unread: {metadata.unread_count}</Text>;
25};