What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={

bg-[url('${path}')] h-screen bg-cover  bg-center text-white border-b-8 border-b-solid border-b-slate-400
}. However, it is throwing an error.

./styles/globals.css:5:0
Module not found: Can't resolve './${path}'

Import trace for requested module:
./styles/globals.css
./pages/_app.js

https://nextjs.org/docs/messages/module-not-found

I also want to include my browse.tsx file

import { GetStaticProps } from "next";
import React from "react";
import { getData } from "./api/randomMovie";
import { getServerSideProps } from "./gr-en";

export default function Browse({ movies }) {
  console.log(movies);
  const { poster_path } = movies;
  const path =
    "https://www.themoviedb.org/t/p/w1280_and_h720_multi_faces/rYFAvSPlQUCebayLcxyK79yvtvV.jpg";
  console.log(path);
  return (
    <div
      className={`bg-[url('${path}')] h-screen bg-cover  bg-center text-white border-b-8 border-b-solid border-b-slate-400`}
    >
      <nav className="grid grid-cols-2 py-2 text-white  bg-black/60">
        <div className="flex col-span-full ml-10">
          <div className="text-white  mt-2 ">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className=""
              fill="none"
              viewBox="0 0 300 81.387"
              width="10vw"
              height="8vh"
            >
              <g fill="#e50914">
                <path d="M256.09 76.212c4.178.405 8.354.84 12.52 1.29l9.198-22.712 8.743 24.807c4.486.562 8.97 1.152 13.44 1.768l-15.328-43.501L299.996 0H287.01l-.135.186-8.283 20.455L271.32.003h-12.822l13.237 37.565-15.644 38.644zM246.393 75.322V0h-12.817v74.265c4.275.33 8.552.684 12.817 1.056M150.113 71.11c3.46 0 6.916.026 10.366.054V43.492h15.397V31.708H160.48v-19.91h17.733V0h-30.6v71.12c.831 0 1.666-.013 2.5-.01M110.319 71.83c4.27-.152 8.544-.28 12.824-,.384V11.8h11.98V.003H98.339V11.8h11.982v60.03h-.002zM12.295 79.772V34.897L27.471 77.96c4.667-.524 9.341-1.017 14.028-1.483V.001H29.201v46.483L12.825.001H0v81.384h.077c4.063-.562 8.14-1.096 12.218-1.613M85.98 11.797V.001H55.377V75.202a1100.584 1100.584 0 0 1 30.578-2.211V61.184c-5.916,.344-11.82,.74-17.71,1.181V43.497h15.397V31.706H68.245V11.797H85.98zM203.614 60.62V-.003h-12.873v71.876c10.24,.376 20.44,.9 30.606,1.56V61.619c-5.9,-.381-11.81,-.712-17.733,-1" />
              </g>
            </svg>
          </div>
          <ul className="flex ml-10 mt-4">
            <li className="mx-2">Home</li>
            <li className="mx-2">TV Shows</li>
            <li className="mx-2">Movies</li>
            <li className="mx-2">New & Popular</li>
            <li className="mx-2">My List</li>
          </ul>
        </div>
        <ul className="flex ml-10 pt-3 col-end-6 mr-10">
          <li className="mx-2">Search</li>
          <li className="mx-2">Kids</li>
          <li className="mx-2">Bell</li>
          <li className="mx-2">User</li>
          <li className="mx-2">My List</li>
        </ul>
      </nav>
    </div>
  );
}

export const getStaticProps: GetStaticProps = async (context) => {
  const movies = await getData();

  console.log(movies);
  return {
    props: { movies },
  };
};


How can I dynamically add a path inside a className using template literals?

Answer №1

It's important to note that in Tailwind, you cannot use string concatenation to generate CSS class names, as discussed in this answer.

To work around this deliberate decision by the Tailwind team and accommodate dynamic styles for each movie, it is recommended to apply the background-image style inline.

<div styles={{backgroundImage:`url(${path})`}} classNames="....">

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

Accessing Stencil through a corporate proxy network

As I embark on my inaugural Stencil project, I've encountered a puzzling error message: Cannot download "https://github.com/ionic-team/stencil- component-starter/archive/master .zip" Check your internet connection Error: connect ETIMEDOUT" De ...

Is there a way to retrieve student data by searching for a specific field?

I have a search button on the front end that allows users to input a student number and retrieve the corresponding information from my schema... Currently, I am mapping the data for all products However, when attempting to log the data, I am getting a nu ...

Modifying the data of a particular object in my rtk asynchronous thunk

I recently started using rtk and immer. I encountered an issue when trying to update my state with redux. For example, when a user logs in, I store their data in redux with the following structure: data = { "user_profile" : { "name&q ...

Steps for implementing a Material-UI transition effect with hover using pseudo classes

My useStyles hook code is meant to create a full-page background that changes on hover, but for some reason it isn't working. I came across a similar solution in CSS which works perfectly. Can you help me figure out the issue? Code snippet that' ...

Encapsulate the HTTP request within a common function for reus

My rest-provider service handles all of my http calls, but I've noticed that each function is repeating a lot of the same http code. It seems like I should create a shared function to avoid this repetition and make it easier to update in the future. ...

`Generate JSON list`

How can I properly encode an array in PHP as JSON, ensuring it includes two variables? $var = 33; $last = 44; Here are the database results: foreach($query->result() as $r) { $data[]= $r; // Fills the array with results } I am attempting to cre ...

Find and retrieve all data attributes with JavaScript

What is the method to retrieve all data-attributes and store them in an array? <ul data-cars="ford"> <li data-model="mustang"></li> <li data-color="blue"></li> <li data-doors="5"></li> </ul> The resultin ...

javascriptDiscover the location of the central point within a polygon

I have stumbled upon a helpful resource that explains how to discover the central point of a polygon (and here in JavaScript): If you want to see a real-life example, check out this jsfiddle demo. Let's work with this specific polygon: var polygon ...

Using PHP, JavaScript, and Bootstrap to display success or error messages for form fields through AJAX

I am working on a form where users input an 'authorisation code' that is then checked against a database using AJAX and PHP. Currently, the form displays a tick if the code is valid and a cross if it is incorrect. I would like to utilize Bootstra ...

What sets apart using "!=" from "=" in the Jade template engine when assigning a variable?

I am a beginner in NodeJS and JS, so please excuse me if this question seems simple. Recently, I came across an example in the ExpressJS documentation that showed how to utilize the Jade template engine. The example included the following lines: html h ...

Issues with synchronizing Firebase and Node.js?

https://i.stack.imgur.com/3fwRO.png Here is the code snippet I used in my Node.js application: for(var v in sna.val()){ console.log("each "+va); console.log(v); var fourthRef = ref.child(val+'/reservation/&apos ...

Looking for a jQuery Gantt Chart that includes a Treeview, Zoom functionality, and editing capabilities?

I am in need of integrating a dynamic Gantt Chart tool into a room booking solution using jQuery. The Gantt chart should be highly interactive, allowing for drag-and-drop functionality, a tree view on the left to group tasks, and a zoom feature for adjusti ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

When passing data to a controller through fetch in Codeigniter 3, the data may sometimes become null

I am facing an issue where I have data that needs to be sent from a view to a controller using fetch, but the data appears as null in the controller despite being successfully sent with a status of 200. Does anyone have a solution to ensure that the data i ...

Issues with the throttling function of the setTimeout method in an

Having some trouble with my timer and function for retrieving data on button clicks. I'm trying to prevent too many rapid requests. Here's the code snippet for the timer: var timer; And the function that updates via AJAX: function doTheTh ...

Transform the image background on mouse hover using CSS

On my php page, I am dynamically visualizing thumbnails. To ensure that they are all the same size, I use the following method: <a class="zoom" href="..."> <img src="thumb/default.png" width="130" style="background-image:url(thumb/<?php echo $ ...

Can you choose an option from a dropdown menu without relying on jQuery?

Can a dropdown list item be selected using AngularJS instead of jQuery? I have successfully accomplished this using jQuery, but I am curious if it can be done with AngularJS. This is how I achieved it using jQuery: var dropdownlist = $("select").data("k ...

Multiple change events triggered in AJAX interactions

Having a list of doctors in a dropdown menu with an ID of "doctors", I use AJAX to fetch related locations based on the selected doctor. These retrieved locations are then displayed in another dropdown menu with an ID of "locations". Subsequently, chan ...

What is the best way to horizontally center a div while ensuring the content within the div stays aligned?

I'm attempting to align a div in the center while maintaining the position of its contents. Check out my code snippet: <style> .wrap{ position: relative; } .character{ position: absolute; bottom: -10%; left: 0; heigh ...

The Reason Behind Angular Error when Using CSS Custom Tags

I have the following SCSS code: main{ width: 100%; height: 840px; /*background: red;*/ margin: 10px auto; position: relative; padding: 5px 0; } section{ width: 98%; height: 600px; margin: auto; display: flex; ...