Integrating ReactJS and Tailwind CSS with Ghost CMS

In this tutorial, we’ll explore how to integrate ReactJS and Tailwind CSS into your Ghost CMS projects. You’ll learn how to set up your environment, customize your theme, and use these tools effectively to improve the functionality and design of your site.

4 min read
Integrating ReactJS and Tailwind CSS with Ghost CMS

This tutorial provides a step-by-step guide to integrating ReactJS and Tailwind CSS within Ghost CMS templates. Adding React can be a powerful way to progressively enhance your site, allowing you to leverage the versatility of one of the most popular JavaScript frameworks for a dynamic and responsive design.

Throughout this tutorial, we’ll be using the Ghost starter theme as our foundation, customizing the rollup.config.js file to enable Tailwind CSS and ReactJS support during the build process. By the end, you’ll have a streamlined setup for applying modern styling and dynamic components in Ghost CMS.

Download the Ghost Starter Theme from GitHub and Install Required Dependencies

To get started, first download the Ghost Starter theme from this GitHub repository. Once downloaded, upload the theme to your Ghost CMS just like any other theme.

Navigate to theme directory and install necessary dependencies:

npm install @rollup/plugin-replace --save-dev
npm install react react-dom
npm install --save-dev @babel/preset-env @babel/preset-react

Edit Rollup config file

Rollup.js is a JavaScript module bundler that compiles small code modules into a larger, optimized bundle for production use. The latest Ghost starter theme uses Rollup as its default bundler, making it easy to manage dependencies and enhance your theme with tools like Tailwind and React.

Edited rollup config file:

import { defineConfig } from 'rollup';
// A Rollup plugin which locates modules using the Node resolution algorithm
import { nodeResolve } from '@rollup/plugin-node-resolve';
// A Rollup plugin to convert CommonJS modules to ES6, so they can be included in a Rollup bundle
import commonjs from '@rollup/plugin-commonjs';
// Use the latest JS features in your Rollup bundle
import babel from '@rollup/plugin-babel';
// Minifies the bundle
import terser from '@rollup/plugin-terser';
// Development: Enables a livereload server that watches for changes to CSS, JS, and Handlbars files
import { resolve } from "path";
import livereload from 'rollup-plugin-livereload';

import replace from '@rollup/plugin-replace'; // Added for react


// Rollup configuration
export default defineConfig({
    input: 'assets/js/index.js',
    output: {
        dir: "assets/built",
        sourcemap: true,
        format: 'iife',
        plugins: [terser()]
    },
    plugins: [
        nodeResolve({
            extensions: ['.js', '.jsx'], // Ensure JSX files are resolved
            browser: true,
        }), 
        commonjs({
            include: [
              'node_modules/**',
            ],
            exclude: [
              'node_modules/process-es6/**',
            ],
            namedExports: {
              'node_modules/react/index.js': ['Children', 'Component', 'PropTypes', 'createElement'],
              'node_modules/react-dom/index.js': ['render'],
            },
          }),
        babel({ 
            babelHelpers: 'bundled',
            presets: ['@babel/preset-react'],
            extensions: ['.js', '.jsx'],
            exclude: 'node_modules/**',
         }),
         replace({
            preventAssignment: false,
            'process.env.NODE_ENV': JSON.stringify(process.env.BUILD === 'production' ? 'production' : 'development'),
            'use client': '' // Add this line to remove the "use client" directive
         }),

        process.env.BUILD !== "production" && livereload({
            watch: resolve('.'),
            extraExts: ['hbs'],
            exclusions: [resolve('node_modules')]
        }),
    ]
})

Install and Configure Tailwind CSS

Tailwind CSS is a popular utility-first CSS framework that provides a robust set of pre-defined classes to help you quickly style web elements. Unlike traditional CSS frameworks, which come with pre-built components, Tailwind focuses on utility classes that can be directly applied in your HTML, giving you precise control over each element’s styling without the need to write custom CSS from scratch.

Within the root directory of the Starter theme, run the following commands to install the required Tailwind tooling:

npm install -D tailwindcss
npm install concurrently

Next, initialize the Tailwind configuration file by executing the following command (it will create tailwind.config.js in theme directory):

npx tailwindcss init 

Edit tailwind.config.js file:

/** @type {import('tailwindcss').Config} */
export default {
  content: ["./*.hbs", "./**/*.hbs", "./assets/js/*.*"],
  theme: {

    extend: {
     
    },
  },
  plugins: [],
}

Now we need to add Tailwind directives inside index.css file. You can find index css in this path: ./assets/css/index.css

@import "vars.css";
@import "components/global.css";
@import "components/forms.css";
@import "components/buttons.css";

/* Ghost components */
@import "ghost/header.css";
@import "ghost/content.css";
@import "ghost/readmore.css";
@import "ghost/members.css";
@import "ghost/errors.css";
@import "ghost/footer.css";
@import "ghost/badge.css";
@import "ghost/pagination.css";
@import "ghost/comments.css";

/* add tailwind */
@tailwind base; 
@tailwind components;
@tailwind utilities;

Editing theme package.json file

The package.json file is crucial for Ghost themes, as it not only manages dependencies and defines project metadata but also facilitates the configuration of various theme settings. This includes customizing active cards in the Ghost editor, specifying image sizes, and adjusting other options tailored to Ghost CMS.

We need to modify the “scripts” section to support Tailwind compilation, enable development reloading, and handle the final building and zipping of the theme.

    "scripts": {
        "dev": "concurrently \"rollup -c --environment BUILD:development -w\" \"npx tailwindcss -i ./assets/css/index.css -o ./assets/built/index.css --watch\" ",
        "build": "rollup -c --environment BUILD:production && npx tailwindcss -i ./assets/css/index.css -o ./assets/built/index.css --minify",
        "zip": "npm run build && bestzip $npm_package_name.zip assets/* partials/* members/* *.hbs package.json",
        "test": "npx gscan .",
        "pretest": "npm run build"
    },

Testing ReactJS Components with Tailwind CSS Classes

Navigate into index.js in this path: ./assets/js/index.js


Delete this line:

import "../css/index.css"

Create basic React component with Tailwind Classes:

import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';


// Render your React component instead
const root = createRoot(document.getElementById('app'));
root.render(<h1 className='text-7xl text-center'>Hello, world from React</h1>);

Create root node for your React app in default.hbs just for testing purposes:

<main class="gh-main">
    {{!-- React Root --}}
    <div id="app"></div>

    {{{body}}}
    {{!-- All content gets inserted here, index.hbs, post.hbs, etc --}}

</main>

Now, by running the Rollup bundler with the command npm run dev, your React app should compile successfully along with Tailwind. You should see both Tailwind and React working seamlessly on the index page.

I hope this tutorial was helpful for devs who are looking how to enhance their Ghost development with ReactJS and Tailwind. Thank you for following along, and happy coding!

Hello 👋

If you have any questions or need help with your project, please don't hesitate to contact us!

 
 
 
 
CZ
EN
EN