Tips for sending images as properties in an array of objects in React

I've been experimenting with various methods to display a background image underneath the "box" in styled components. How can I pass an image as a prop into the background image of the box with the image stored in the array of objects? I'm unsure if it's a syntax issue or if this functionality is not supported. Any assistance would be highly appreciated!


import styled from "styled-components";
import px2vw from "../../../../utils/px2vw";
import {StyledIconBase} from '@styled-icons/styled-icon'
import travelImg from  "./travelBackground2.png";

export const BackgroundImage = styled.div`
    border: 1px solid #000;
    background-repeat: no-repeat;
    width: 100%;
    height: 850px;;
`;

export const IconStyleWrapper = styled.div`
  ${StyledIconBase} {
    height: 35px;
    width: 35px;
    padding-left: ${px2vw(42)};
  }
`

// Other styled components...


import React from "react";
import styled from "styled-components";
import { Container, Box, BoxTitle, BoxText, Header, HeaderLinks, HeaderText, HeaderOffSet, BackgroundImage } from "./styles/HomeStyles"

export const boxData = [
  {
    id: 0,
    title: "Travel",
    text: "Check out some Travel Stories!",
    bgColor: "#D5CAFA",
    hoverColor: "#e3dcfa",
    image: require("./styles/travelBackground2.png"),
    link: "travel"
  },
  // Other box data entries...
];

const headerData = [
  {
    id: 0,
    text: "Articles",
    link: "/articles"
  } ,
  // Other header data entries...
]

export default function HomePage() {
  return (
    <div class="background">

    <Header>
      <HeaderOffSet>
      Kyle Longrich
      </HeaderOffSet>
      {headerData.map(data => (
        <HeaderLinks>
          <HeaderText key={data.id} as="a" href={data.link}> {data.text} </HeaderText>
        </HeaderLinks>
      ))}
    </Header>
    <Container>
      {boxData.map(box => (
        <Box key={box.id} bgColor={box.bgColor} BackgroundImage={box.image} as="a" href={box.link}>
          <BoxTitle>{box.title}</BoxTitle>
          <BoxText>{box.text}</BoxText>
        </Box>
      ))}
    </Container>  
    </div>
  );
}

Answer №1

It was necessary to modify the image tag in the second document.

import journeyImage from "./styles/journeyBackground2.png"

{
    id: 0,
    title: "Journey",
    text: "explore some Journey Stories!",
    bgColor: "#D5CAFA",
    hoverColor: "#e3dcfa",
    image: journeyImage,
    link: "journey"
  }

Answer №2

It is recommended that component props do not begin with an uppercase letter. Let's start by making the necessary adjustments:

<Box key={box.id} bgColor={box.bgColor} BackgroundImage={box.image} as="a" href={box.link}>

should be changed to

<Box key={box.id} bgColor={box.bgColor} backgroundImage={box.image} as="a" href={box.link}>

Within the boxData, utilize the image imported at the beginning instead of using require to import the same image again. Update the code from:

{
    id: 0,
    title: "Travel",
    text: "check out some Travel Stories!",
    bgColor: "#D5CAFA",
    hoverColor: "#e3dcfa",
    image: require("./styles/travelBackground2.png"),
    link: "travel"
},

to:

{
    id: 0,
    title: "Travel",
    text: "check out some Travel Stories!",
    bgColor: "#D5CAFA",
    hoverColor: "#e3dcfa",
    image: travelImage,
    link: "travel"
},

Now you can reference the backgroundImage prop within Box like this:

export const Box = styled.div`
  display: flex;
  //...style stuff
  background-image: `url(${props.backgroundImage})`

If this doesn't work, you can directly add a style attribute to Box, for example:

<Box style={{backgroundImage: `url(${travelImage})`}}>

I understand that inline styles may not be ideal, but this approach can help identify the issue more effectively.

Cheers! 🍻

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

Changing pages in Django with a single click of a line: A step-by-step guide

As a beginner in Django, I am looking to create views that change when a line in an HTML tag is clicked. The idea is to open a new view named after the hash inside the <code>Hash tag. {% load staticfiles %} <!DOCTYPE html> <html lang="fr"&g ...

Is it possible to utilize the spread operator for combining arrays?

Consider two different arrays represented by variables a and b. The variable c represents the output as a single array, indicating that this method combines two or more arrays into one. let a=[a ,b]; let b=[c ,d]; c=[a,...b] The resulting array will be: ...

Updating the AngularJS view following a deletion process

I have a web application developed using AngularJS and Rails that carries out RESTful operations like create, read, and delete. After deleting an item, I need to refresh the page and update the view asynchronously. However, I am facing challenges in imple ...

Utilizing the same NextJs page layout, showcase varying sets of information

As I work on my Next.js app, I am faced with the challenge of creating two pages that share the same design but present different data. What is the most effective way to achieve this while ensuring that each page has a unique URL path? ...

ReactJS component disappearing behind the Navbar

When using my React app, I have a navigation bar at the top. The Navbar component is called in App.js, and the code snippet below shows how it is implemented. export default function App() { return ( <Router> <Fragment> ...

Is there a way in Jquery to remove a class?

I have created a code for a single page website where clicking on the toggle bar will display the 'ul' and clicking on one of the 'a' links will take me to the corresponding div. I want the toggle bar to automatically close back after c ...

Tips on utilizing the useState hook for storing numerous key objects?

Currently, I am working with a candlestick chart for a cryptocurrency that displays data over different timeframes such as 1 minute and 30 minutes. Below is the code snippet that sets the initial state to show a 1-hour chart when a user first visits: const ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

What is the method for enlarging an element without regard to surrounding elements?

I am working on a code where I want the element to zoom in when hovered, completely disregarding its normal flow. By "ignoring its flow," I mean that other elements like tags might obstruct parts of its content. https://i.sstatic.net/NBoez.png https:// ...

Troubleshooting an expressjs server in parallel with electron

I have managed to successfully run an ExpressJS server alongside Electron by following the instructions provided in this post: Run Node.js server file automatically after launching Electron App However, I am facing an issue where there is no output from t ...

PHP: I am unable to establish a connection with the script or submit form data to mySQL

Seeking assistance with debugging this script. (The * represents confidential information that I am aware of but cannot share) <?php $dbhost = '*********'; $dbuser = '*********'; $dbpass = '*********'; $conn = mysql_conne ...

Dividing a set of information using Ajax

I am faced with a challenge where I have a list containing 4 data points from a Python script that is called by an Ajax function. The issue at hand is figuring out the method to separate this data because each piece of information needs to be sent to separ ...

Why does attempting to access an undefined property not trigger an error?

I am curious to know why var myVar = unDef; may trigger a ReferenceError, while var myObj = {}; var myVar = myObj.unDef; runs smoothly? It simply returns undefined without any runtime issues. Despite both not being defined. ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

What is the best way to transfer attribute values from multiple elements and paste them each into a separate element?

I have multiple elements with the tag <a class="banner2">. Each of these elements has a different URL for the background image and href value. <a href="#" target="_blank" class="banner2" style="background-image:url('<?php echo get_templat ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...

Getting rid of mysterious Google Analytics script from WordPress

My client has requested that I incorporate Google Analytics into her website. After accessing her Google account, I attempted to paste the tracking code into the appropriate section of the Wordpress plugin. To my surprise, the code did not work as expect ...

Step-by-step guide to creating a clickable div

Having an issue with around 200 clickable buttons on my website, all designed the same: <div> <asp:hyperlink> //or LinkButton </div> The background-style of the button is within the Div and the text of the button is in Hyperlink / LinkB ...