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)
- An APNS channel with a workflow that produces push notifications (optional)
Installation
- Via NPM:
npm install @knocklabs/react-native
- Via Yarn:
yarn add @knocklabs/react-native
Configuration
To configure the feed you will need:
- A public API key (found in the Knock dashboard)
- A user ID, and optionally an auth token for production environments
- If integrating an in-app feed, a feed channel ID (found in the Knock dashboard)
- If integrating push notifications, an Expo channel ID (found in the Knock dashboard)
Usage
You can integrate the feed into your app as follows:
1import {
2 KnockProvider,
3 KnockFeedProvider,
4 NotificationFeedContainer,
5} from "@knocklabs/react-native";
6
7const YourAppLayout = () => {
8 const [isVisible, setIsVisible] = useState(false);
9 const notifButtonRef = useRef(null);
10
11 return (
12 <KnockProvider apiKey={process.env.KNOCK_PUBLIC_API_KEY} userId={userId}>
13 {/* Optionally, use the KnockFeedProvider to connect an in-app feed */}
14 <KnockFeedProvider feedId={process.env.KNOCK_FEED_ID}>
15 <NotificationFeedContainer>
16 <Text>Notifications go in here!</Text>
17 </NotificationFeedContainer>
18 </KnockFeedProvider>
19 </KnockProvider>
20 );
21};
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};