What is the best way to implement a background image onto a card using state in React?

Currently, I have a React application with three cards on a single page. While I've successfully mapped the titles and text content to these cards, I'm struggling to figure out how to map background images to each card using the planet object. How would I go about setting the imported images as the background of each card?

import React, { Component } from "react";
import { Link } from "react-router-dom";
import mars from "../images/mars.jpg";
import venus from "../images/venus.jpg";
import titan from "../images/titan.jpg";

export default class Planets extends Component {
  state = {
    planets: [
      {
        planet: "",
        title: "Mars",
        info: "red planet"
      },
      {
        planet: "",
        title: "Venus",
        info: "gaseous planet"
      },
      {
        planet: "",
        title: "Titan",
        info: "moon"
      }
    ]
  };

  render() {
    return (
      <section style={{ backgroundColor: 'black', height: '100vh' }} className="planets">
        <div className="planets-center">
          {this.state.planets.map(item => {
            return (
              <Link to="/rooms">
                <div className="planets-card" style={{ backgroundImage: `url(${item.image})` }}>
                  <article key={`item-${item.title}`} className="planets">
                    <h6>{item.title}</h6>
                    <p>{item.info}</p>
                  </article>
                </div>
              </Link>
            );
          })}
        </div>
      </section>
    )
  }
}

Answer №1

Include the images in the state and define them as backgroundImage using the style prop

<div className="planets-card" style={{ backgroundImage: `url(${item.bgUrl})` }}>

For example (not tested):

import mars from "../images/mars.jpg";
import venus from "../images/venus.jpg";
import titan from "../images/titan.jpg";

export default class Planets extends Component {
  state = {
    planets: [{
        planet: "",
        title: "Mars",
        info: "red planet",
        bgUrl: mars,
      },
      {
        planet: "",
        title: "Venus",
        info: "gaseous planet",
        bgUrl: venus,
      },
      {
        planet: "",
        title: "Titan",
        info: "moon",
        bgUrl: titan,
      }
    ]
  };


  render() {
    return (
     <section style={{
        backgroundColor: 'black', height: '100vh'}} className="planets">
        <div className="planets-center">
          {this.state.planets.map(item => {
            return (
              <Link to="/rooms">
                <div className="planets-card" style={{ backgroundImage: `url(${item.bgUrl})` }}>{item.icon}
                  <article key={`item-${item.title}`} className="planets">
                    <h6>{item.title}</h6>
                    <p>{item.info}</p>
                  </article>
                </div>
            </Link>
            );
          })}
        </div>
      </section>
    )
  }
}

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

Consistent CSS alignment across all browsers

I have designed a four-digit counter that needs to be displayed in the bottom right corner of the page. Each digit is represented by a block image as a background. It is functioning properly in Chrome, but there are compatibility issues with IE7+ and Firef ...

How can I obtain hosting XULDocument for a ContentWindow or HTMLDocument within a Firefox extension?

I have a Firefox Extension with a XUL overlay that includes some Javascript with event handlers. One of these event handlers is an EventListener for DOMContentLoaded. I want to load a second overlay only when visiting a specific website. Here is a snippet ...

Guide on creating a readUInt16BE function in a Node.js environment

Looking to implement the readUint16BE function in node.js, here's how it is declared: buf.readUInt16BE(offset, [noAssert]) Documentation: http://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert This function reads an unsigned 1 ...

Adjustable annotations in flot chart

When creating a flot, I can draw segments by specifying the markings in the options. markings: [ { xaxis: { from: 150, to: 200 }, color: "#ff8888" }, { xaxis: { from: 500, to: 750 }, color: "#ff8888" } ] Now, I am looking to remove these existing m ...

Updating the state does not reflect on the user interface

I'm a beginner in React and I've encountered an issue that I can't seem to figure out. I created a Component called ShoppingCart which is supposed to display all the products added to the cart: ShoppingCart.jsx file: import React, { Compo ...

Concealing photos only to reveal them in an elegant fancybox display

I am looking to create a hidden gallery that can be displayed in fancybox. The idea is for visitors to click on one image and then have the ability to view more "hidden" pictures within fancybox. I know this can be accomplished by showing links or images ...

Troubleshooting Problems with display:table and display:table-cell Alignment in Internet Explorer Versions 7 and 9

I have been struggling with the layout of a website that contains multiple columns. After extensive work, I believed I had everything properly aligned. Adobe BrowserLab seemed to confirm this, aside from various issues in IE6 and IE7 which I decided to ove ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

The presence of &#65279; is seen in textarea elements, but it is not found

Currently, I am in the process of developing an autocomplete feature for a textarea. While there are existing autocomplete solutions available, I decided to create my own from scratch. The autocomplete functionality works smoothly, except for one issue th ...

Tips for extending the server timeout duration on Apisauce

Is there a way to increase the server timeout for requests that take longer than 30 seconds but can still be completed within that time frame? I've tried adjusting the timeout in the config file without success ...

Style the image within the table by setting a specific width

My table contains a mix of images and text, with the images set to a specific width using the code snippet below: <img src="" width="250"> When certain large images are dynamically added to the table during runtime using jQuery, the table's wi ...

Performing computations within a loop and ways to retrieve the total of the elements in Vue.js

Starting out as a newcomer to JavaScript, I am seeking guidance on how to effectively incorporate it into my current project. I'm tasked with creating a sophisticated financial calculator within my already existing PHP financial instrument. The goal ...

The regular expression is not matching the expected pattern

Here is an interesting scenario involving a Javascript regular expression matching operation: "class1 MsoClass2\tmsoclass3\t MSOclass4 msoc5".match(/(^|\s)mso.*?(\s|$)/ig); When running this operation, the expected result would be [" ...

Condition has been fulfilled for both ngShow and ngHide

I am attempting to show a loading icon while data is being loaded, and then display the data once it is ready. However, I am encountering a problem where for a brief moment, both the loading icon and the data are visible... https://i.sstatic.net/vDXOG.png ...

Error message is prompted on React Redux form input editing due to uncontrolled input

React Redux: Issue with form input editing results in error message for an uncontrolled input When using React Redux to display a record in a form input from the database, everything worked fine. However, upon trying to edit the form input for the lastnam ...

What sets React apart in terms of indicating 'const' or 'let' within the render() function compared to using class extends component { render() {} }?

Can you explain the contrast between defining const within class App extends Component { --- This spot ---- render() { And doing it like this? render() { ---- Here ----- return ( Additionally, is there a way to change 'const' o ...

Make sure not to establish a Socket.io connection more than once

I am currently using React on the frontend and Express on the backend. The code snippet below is what I have written to establish a connection between the client and the server: import React, { useEffect, useState } from 'react'; import { io } f ...

Got an unexpected value of `false` for the non-boolean property `className` in ReactJS

A component has the following code snippet: An error is encountered: Received false for a non-boolean attribute className. export default function TodoItem({ todo }) { const dispatch = useDispatch() return ( <li className={todo.completed & ...

When making a jQuery + AJAX request, IE8 is causing a null return value

I'm completely stumped as to why this issue is happening. To start, the code has been checked and validated by the W3C validator as HTML5, except for some URL encoding problems (such as & needing to be &amp;), but I don't have the ability ...

Can React application be set up to utilize Kubernetes container's environment variables?

Imagine having a React application that you want to deploy to three different environments - dev, test, and production. Each environment requires different API addresses, which need to be stored as environment variables. As a forward-thinking developer, y ...