Having trouble with Tailwind custom background image not displaying correctly when the website is live

When working on my CRA project, I encountered an issue with background images not appearing in the production environment. Despite adding custom background images by modifying the theme.backgroundImage section of my tailwind.config.js file, the images only show up locally and not in production. It seems that the CSS class (e.g., bg-1989) is being applied but is not actually adding a background-image property.

// tailwindcss.config.js
module.exports = {
  theme: {
    extend: {
      backgroundImage: theme => ({
        '1984':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_1984.jpg')",
        '1989':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_1989.jpg')",
        '1997':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_1997.jpg')",
        '2003':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_2003.jpg')",
        '2014':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_2014.jpg')",
        '2019':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_2019.jpg')",
        '2020':
          "linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('./images/Homepage_2020.jpg')"
      })
    }
  }
};

I am utilizing these images as shown below:

        <div className={`hero-image bg-${year.id}`}>
          <div className="small-headline text-white absolute w-full scene-name">
            <Container className="grid__container">
              <Row className="grid__row">
                <Col lg={2} />
                <Col lg={6}>{year.title}</Col>
                <Col lg={4}>{year.id}</Col>
              </Row>
            </Container>
          </div>
        </div>
// package.json
{
  "name": "on-borrowed-time",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "express": "^4.17.1",
    "node-sass": "^4.14.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-grid-system": "^7.1.1",
    "react-html-parser": "^2.0.2",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  .
  .
  .
  "devDependencies": {
    "autoprefixer": "^9.8.6",
    "postcss": "^7.0.36",
    "prettier": "^1.19.1",
    "sass": "^1.30.0",
    "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.2.4"
  }
}

Answer №1

In my understanding, tailwind will only load the classes that are actually used and not all classes. So, when you are dynamically changing classes at runtime, there may be some classes that are missing. One way to address this issue is by adding divs with the dynamic classes like shown below.

<div className={"bg-1984 hidden"}> </div>
<div className={"bg-1989 hidden"}> </div> 
<div className={"bg-1997 hidden"}> </div> 
<div className={"bg-2003 hidden"}> </div> 
<div className={"bg-2014 hidden"}> </div>
<div className={"bg-2019 hidden"}> </div>
<div className={"bg-2020 hidden"}> </div>

This approach worked for me, but I am unsure if there is a more optimal solution available.

Answer №2

Design a secure list of dynamically produced class names that can be used during execution.

// tailwind.config.js
module.exports = {
  safelist: [
    'bg-1984',
    'bg-1989',
    // ...
    'bg-2020',
  ],
  // ...
};

Answer №3

Considering Reggie's safelist approach could be beneficial in solving the production issue at hand. Nevertheless, it is crucial to confirm beforehand that there are no dynamic generation of classes like bg-${year.id}. It would be more efficient to predefine these classes and incorporate the variable as a complete class, following the guidelines stated in the documentation: https://tailwindcss.com/docs/content-configuration#dynamic-class-names

Rather than using bg-${year.id}, consider using something similar to the following inline code:

{year.id === 1984 ? 'bg-1984' : ''}

This method allows for dynamic background display while ensuring Tailwind recognizes the complete class name, preventing inconsistency.

In scenarios where there are numerous options (years) involved, it may be practical to generate this functionality within a separate function instead of directly inline.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

Avoiding Default Slice Behavior in React and Redux When Navigating Websites

I am looking to create a slice that represents a user. The values of the slice will be set when the user logs in. However, there is an issue: Whenever you move around the site, the slices and states reset to their defaults. This results in it appearin ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...

This hyperlink is not redirecting to an external website

I recently downloaded a one pager template that has a unique design. All the hyperlinks within the template are set to link to specific sections on the page and use a data-link="" parameter. However, I encountered an issue when trying to link one of the m ...

Tips for implementing two Secondary Actions in React Material UI, with one positioned on the left corner and the other on the right, while ensuring that the behavior of the

Is there a way to display two secondary actions on either end of a list item without triggering additional onclick events? The placement can be adjusted by overriding the CSS properties right and left. https://i.stack.imgur.com/rhr7N.gif The issue arises ...

Using moment with material-ui-pickers KeyboardDatePicker: A simple guide

Utilizing the KeyBoardDatePicker component provided by material-ui-pickers alongside the moment utils for a DatePicker. import React, { Fragment, useState } from "react"; import { MuiPickersUtilsProvider, KeyboardDatePicker } from "@material-ui/picker ...

Shopping cart with Redux implemented in React.js

Why do I encounter an issue where clicking "Add to cart" only registers a single change even after multiple clicks, and the item doesn't get added to the cart? How can this be resolved? The desired functionality is for the 'cart' array to st ...

Transferring information from HTML to React and Redux

Currently, the backend server is generating an HTML page that includes a javascript object named MY_DATA and the root element for the React/Redux app: <script> MY_DATA = { foo: 'bar' } </script> <div id="app"></div> ...

What is the best way to position an image beside a jquery dialog box?

Apologies for not finding a suitable topic to discuss. Is it possible to place an image next to a jQuery dialog, similar to the following example? If so, how can this be achieved? ...

What are the steps to make the chosen title and its content active while deactivating the others?

I am currently developing a website for an educational institution that includes schools with subdivisions such as matric, CBSE, and state board, as well as a college. My goal is to create a user interface where clicking on a specific stream (such as matri ...

Using Div in Bootstrap to Overlay Text on an Image

Trying to overlay text on an image using the code snippet below; https://i.sstatic.net/7jkEC.png <div class="wrapper"> <img src="https://cdn0.vox- cdn.com/thumbor/qLH7593e3D2SSSIdkwgBWdYhjjk=/289x0:802x684/400x533/filters:forma t(webp)/cdn0.vo ...

Why isn't my state updating with componentDidMount()?

I am currently exploring React and working on creating a view counter for different divs. To achieve this, I require the height and scroll top height of the divs. However, after obtaining these values, I am facing issues when trying to set state with the ...

What is the best way to eliminate gridlines or borders in a React-Data-Grid component?

Is there a way to remove gridlines from a simple table? You can view the code in this codesandbox demo: https://codesandbox.io/s/rdg-cell-editing-u2ood. I'm wondering if I need to manually override internal CSS classes or if there's a specific p ...

What is the best way to mark a MenuItem as active within a Material UI Drawer component?

Here is the code snippet I am working with: <Drawer docked = {false} width = {330} open = {this.state.drawerOpen} onRequestChange = {(drawerOpen) => this.setState({drawerOp ...

Issue found in Bootstrap-Multiselect plugin: The dropdown menu appears beneath the outer container when overflow-y is applied

My experience with using Bootstrap-Multiselect and encountering an issue where the dropdown disappears when the outer container has overflow-y: scroll and a max-height has prompted me to seek solutions. I am looking for a way to ensure that the dropdown is ...

accessing a ReactJS web application through a .NET web application

Here's the situation: We have a large predeveloped .Net web portal and a smaller project built in ReactJs. My goal is to call my React project from within the .Net page. Is this feasible? It's important to mention that both portals are hosted o ...

Styling a div element in React

Just dipping my toes into the world of styling here, so bear with me. I'm currently working on a React app and attempting to bring an image from a file using the following code: import cup from './img/cup.png' My goal is to style it in co ...

Customizing MUI radio buttons to display tick icons instead of bullets

Looking to replace the bullet icon with CheckCircleSharpIcon from '@mui/icons-material/CheckCircleSharp' {res?.map((radiooption, index) => ( <> <RadioGroup aria-labelledby="demo-radio-buttons-group-label" name="radio-bu ...

Positioning an image beneath the navigation bar in Bootstrap and CSS without it getting covered by text

I am having difficulty positioning an image below the navbar without it overlapping with the text in the navbar. No matter what I try in my code, the image remains attached to the bottom of the navbar and won't move to a separate row below it. I hav ...

Custom-designed background featuring unique styles

I have implemented the following code to create a continuous running banner: <style> #myimage { position: fixed; left: 0%; width: 100%; bottom: 0%; background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bild ...