How To Integrate CMS To A ReactJS Site

  • Sun Jan 12 2020
  • Sibtay Shah

In this post we are going to integrate a CMS to a custom ReactJS site. I will use the CMS for a blog, however you can use the same approach for any other custom CMS needs, for example, for content in the website pages, your mobile app or Alexa skill

Create The ReactJS App

Lets start by first creating a sample ReactJS app.

npx create-react-app <app-name>

Then cd into the directory

cd <app-name>

And start the app

npm start

Next lets install the React Router module so that we could setup some routes

npm install --save react-router-dom

Setup Sanity

Install sanity CLI

npm install -g @sanity/cli

Initialize the sanity project

sanity init

You will be asked to login to sanity. After successful log in, select create a new project and select the blog schema

Next cd into the sanity project and start the studio

cd <sanity-project-name>
sanity start

This should bring up local version of the sanity studio.

Create Your First Post

From the studio, do the following

  • Create an author
  • Create a category
  • Then create the post, populating all the required fields
  • Publish

Deploy Sanity

Next we will deploy our sanity project to sanity's default hosting environment. Just run the following command

sanity deploy

Once deployment completes URL to the studio would be outputted. Visit the URL. Congrats! your blog is live!

Frontend Code Changes

Lastly make the following code changes in the frontend app. The details are explained in the video above

SanityClient.js

const sanityClient = require('@sanity/client')

const client = sanityClient({
  projectId: '<your_project_id>',
  dataset: '<your_data_set>',
  useCdn: true // `false` if you want to ensure fresh data
});

export default client;

BlogArticle.js

Actual component that renders the blog post itself

import React from 'react';
import {withRouter} from 'react-router';
import client from "./SanityClient";

const BlockContent = require('@sanity/block-content-to-react');

const serializers = {
  types: {
    code: props => (
      <pre data-language={props.node.language}>
        <code>{props.node.code}</code>
      </pre>
    )
  }
}

class BlogArticle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      article: null
    }
  }
  
  async retreiveArticle(articleSlug) {
    const query = '*[_type == "post" && slug.current == $postSlug]'
    const params = {postSlug: articleSlug};
    var articles = await client.fetch(query, params);

    // TODO: check articles size here
    this.setState({ article: articles[0]});
  }

  componentDidMount() {
    var articleSlug = this.props.match.params.articleSlug;
    this.retreiveArticle(articleSlug);
  }
  renderArticle(article) {
    return (
      <div>
        <h1>{article.title}</h1>
        <BlockContent blocks={article.body} serializers={serializers}>
        </BlockContent>
      </div>
    )
  }
  render() {
    return (
      <div className="BlogArticle" style={{padding: "40px", textAlign: "left" }}>
        {!this.state.article && "Loading..."}
        {this.state.article && this.renderArticle(this.state.article)}
      </div>
    )
  }
}

export default withRouter(BlogArticle);

Blog.js

A Component that lists out the blog posts

import React from 'react';
import {Link} from "react-router-dom";
import client from "./SanityClient";

class Blog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }
  componentDidMount() {
    this.getBlogArticles();
  }
  async getBlogArticles() {
    const query = '*[_type == "post"]'

    var articles = await client.fetch(query);
    this.setState({ articles: articles });  
  }
  render() {
    return (
      <div>
        {!this.state.articles && "Loading..."}
        {this.state.articles && this.state.articles.map((article, index) => {
          return (<p key={index}><Link to={"/blog/" + article.slug.current}>{article.title}</Link></p>)
        })}
      </div>
    );
  }
}

export default Blog;

App.js

import React from 'react';
import './App.css';
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from "react-router-dom";
import Blog from './Blog';
import BlogArticle from './BlogArticle';

function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route exact path="/">
            <Blog />
          </Route>
          <Route path="/blog/:articleSlug">
            <BlogArticle />
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

export default App;