← Back

Building A Web App With Headless CMS And React

By Vivek Singh
Picture of the author
Published on
Headless CMS and React

Creating a modern web application often requires a combination of flexibility, scalability, and a seamless content management experience. One powerful approach to achieving this is by using a headless Content Management System (CMS) alongside a robust front-end framework like React. In this blog post, we’ll explore the steps to build a web app using a headless CMS and React, from setting up the environment to deploying your application.

What is a Headless CMS?

A headless CMS is a content management system that provides a way to manage and deliver content without a built-in front-end interface. Instead, it offers content through an API, allowing developers to build the front end with any technology they prefer. This decoupling of the front end and back end offers greater flexibility and control over how content is displayed.

Benefits of Using a Headless CMS with React

  1. Flexibility: You can use any front-end framework or library to present your content.
  2. Scalability: Easily scale your application by leveraging modern JavaScript frameworks.
  3. Performance: Optimize the performance of your web app by decoupling the front end and back end.
  4. Security: Enhanced security as the CMS is not directly exposed to end users.

Choosing a Headless CMS

There are several headless CMS options available, including:

  • Strapi
  • Contentful
  • Sanity
  • Ghost

For this tutorial, we’ll use Contentful due to its intuitive interface and robust API.

Setting Up Your Environment

Prerequisites

  • Node.js installed
  • Basic knowledge of React and JavaScript
  • A Contentful account

Step 1: Create a Contentful Space

  1. Sign up for a Contentful account and create a new space.
  2. Define your content models (e.g., Blog Post, Author).
  3. Add content entries for your models.

Step 2: Initialize Your React Project

  1. Open your terminal and create a new React project using Create React App:

    npx create-react-app headless-cms-react
    cd headless-cms-react
    
  2. Install necessary dependencies:

    npm install @contentful/rich-text-react-renderer @contentful/rich-text-types contentful
    

Step 3: Configure Contentful

  1. Create a new file called contentful.js in the src directory:

    import { createClient } from 'contentful';
    
    const client = createClient({
        space: process.env.REACT_APP_CONTENTFUL_SPACE_ID,
        accessToken: process.env.REACT_APP_CONTENTFUL_ACCESS_TOKEN,
    });
    
    export default client;
    
  2. Add your Contentful space ID and access token to a .env file:

    REACT_APP_CONTENTFUL_SPACE_ID=your_space_id
    REACT_APP_CONTENTFUL_ACCESS_TOKEN=your_access_token
    

Step 4: Fetch and Display Content

  1. Create a new component called BlogPost.js:

    import React, { useEffect, useState } from 'react';
    import client from './contentful';
    
    const BlogPost = () => {
        const [posts, setPosts] = useState([]);
    
        useEffect(() => {
            client.getEntries({ content_type: 'blogPost' })
                .then(response => setPosts(response.items))
                .catch(console.error);
        }, []);
    
        return (
            <div>
                {posts.map(post => (
                    <div key={post.sys.id}>
                        <h2>{post.fields.title}</h2>
                        <p>{post.fields.content}</p>
                    </div>
                ))}
            </div>
        );
    };
    
    export default BlogPost;
    
  1. Import and use the BlogPost component in App.js:

    import React from 'react';
    import BlogPost from './BlogPost';
    
    function App() {
        return (
            <div className="App">
                <header className="App-header">
                    <h1>My Blog</h1>
                </header>
                <main>
                    <BlogPost />
                </main>
            </div>
        );
    }
    
    export default App;
    

Step 5: Style Your Application

  1. Add some basic CSS to style your application. Create a styles.css file and import it in App.js:

    .App-header {
        background-color: #282c34;
        padding: 20px;
        color: white;
        text-align: center;
    }
    
    .BlogPost {
        margin: 20px;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 8px;
    }
    
    .BlogPost h2 {
        margin-top: 0;
    }
    

    Import the CSS file in App.js:

    import './styles.css';
    

Step 6: Deploy Your Application

To deploy your React application, you can use services like Vercel, Netlify, or GitHub Pages. For instance, to deploy with Vercel:

  1. Install the Vercel CLI:

    npm install -g vercel
    
  2. Initialize and deploy:

    vercel
    

Follow the prompts to complete the deployment process.

Conclusion

Building a web app with a headless CMS and React allows for a powerful, flexible, and scalable solution for content management and presentation. By decoupling the front end and back end, you gain more control over your content delivery and can easily adapt to changing requirements. With tools like Contentful and React, you can create dynamic, content-driven web applications with ease.

Feel free to expand this basic setup with more features such as routing, additional content types, or even adding rich media content. The possibilities are endless!

Related Posts

Stay Tuned

Want to become a Full-Stack pro?
The best articles, links and news related to web development delivered once a week to your inbox.