Build a Website with React and Tailwind CSS

1.Setting Up React and Tailwind CSS

First, create a React project with

npx create-react-app react-shop

Then, change directory to the created project:

cd react-shop

Next, we’ll install the dependencies required for Tailwind CSS:

npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

2.Setting Up CRACO

We need CRACO here to override PostCSS configurations and add the tailwindcss plugin. So, let’s first install it:

npm install @craco/craco

When using CRA, the scripts in package.json look like this:

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
}

As we’re using CRACO to do what we can’t do with CRA by default, we need to change the scripts to use CRACO for building the project or running it in development:

"scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test",
  "eject": "react-scripts eject"
},

Next, create the CRACO configuration file craco.config.js in the root of the project:

module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
}

Now we’ll generate the configuration file for Tailwind CSS:

npx tailwindcss init

This will create the file tailwind.config.js in the root of the project. It will have the following content:

module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

The final step in setting up our React project with Tailwind CSS is to include some of the Tailwind CSS styles in src/index.css. Replace the contents of this file with the following:

@tailwind base;
@tailwind components;
@tailwind utilities;

The @tailwind directive basically imports the styles into index.css. And by default, CRA imports src/index.css in src/index.js:

import './index.css';

This means that Tailwind CSS styles will be applied in our React project, and we’re ready to start building a beautiful website!

Leave a comment

Your email address will not be published. Required fields are marked *