Skip to main content

Using with React

Integrating MongoDB Stitch (now MongoDB Realm) with a React application involves several steps. Below is a step-by-step guide to help you through the process:

Prerequisites

  • A MongoDB Atlas account and a cluster
  • A MongoDB Realm (Stitch) app linked to your cluster
  • Node.js and npm installed on your machine
  • A React app (you can create one using create-react-app if you don't have one)

Step 1: Install MongoDB Stitch SDK

First, you'll need to install the MongoDB Stitch SDK. Open your terminal and navigate to your React project directory, then run:

npm install mongodb-stitch-browser-sdk

Step 2: Initialize Stitch Client

In your React app, initialize the Stitch client. You'll need the App ID from your MongoDB Realm dashboard.

import { Stitch, AnonymousCredential } from 'mongodb-stitch-browser-sdk';

const client = Stitch.initializeDefaultAppClient('<Your-App-ID>');

Place this code in a file where it will be executed when your app starts, such as index.js.

Step 3: User Authentication

For demonstration, let's use anonymous authentication.

client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
console.log(`Logged in as anonymous user with id: ${user.id}`);
});

You can place this in a useEffect if you're using functional components or componentDidMount if you're using class components.

Step 4: Interact with MongoDB

Now you can perform CRUD operations. To insert a document into a collection:

const db = client.getServiceClient(RemoteMongoClient.factory, 'mongodb-atlas').db('mydatabase');
const collection = db.collection('mycollection');

collection.insertOne({ name: 'React User', age: 25 })
.then(result => {
console.log(`Successfully inserted item with _id: ${result.insertedId}`);
});

Step 5: Use in Components

You can now use the Stitch client in your React components to fetch data, authenticate users, or perform any other actions.

// Fetch data from MongoDB and set it to state
useEffect(() => {
collection.find({}).asArray()
.then(docs => {
// Set your state here
});
}, []);

Step 6: Deploy and Test

Once you've integrated all the features you need, deploy your React app and test it to ensure everything is working as expected.