ReactJS and Webpack: Troubleshooting image display issues

I am having trouble loading a background image in my component. Despite using require('imagepath') to load the image, it gets changed to url('imagepath') during build. However, when I try to load it within my styles that are being added to the theme, the image does not render properly. I have to resort to a workaround solution for this issue (refer to background image). What could be causing this problem?

 import React, { Component } from 'react';
import '../styles/App.css';
import CssBaseline from '@material-ui/core/CssBaseline';
import Grid from '@material-ui/core/Grid';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card'
import CardHeader from '@material-ui/core/CardHeader'
import CardActions from '@material-ui/core/CardActions'
import Button from '@material-ui/core/Button'
import Image from './brisket.jpg'


const styles = theme => ({
  '@global': {
    body: {
      height: '100%'
    }
  },
  card: {
    backgroundImage: "url(" + require('./wood_background.jpg') + ")",
    flexGrow: 1,
    justify: 'center',
    minHeight: '100vh',
  },
  cardHeader: {
    backgroundColor: theme.palette.grey[200],
  }
})

const cards = [
  {
    title: 'Start Smoking',
    buttonText: 'Let\'s get started',
    buttonVarient: 'contained'

  }
]

class Intro extends Component {
  render() {
    const { classes } = this.props;
    return (
      <React.Fragment>
        <CssBaseline />
          <Grid container className={classes.card} alignItems='center' justify='center' spacing={40}>
            {cards.map(card => (
              <Grid item key={card.title} md={4}>
                <Card>
                  <CardHeader
                    title={card.title}
                    titleTypographyProps={{ align: 'center' }}
                    className={classes.cardHeader}
                  />
                  <CardActions>
                    <Button fullWidth variant={card.buttonVarient} color='primary'>
                      {card.buttonText}
                    </Button>
                  </CardActions>
                </Card>
              </Grid>
            ))}
          </Grid>
      </React.Fragment>
    );
  }
}

export default withStyles(styles)(Intro);

Answer №1

To use the image, first import it and then assign it to the backgroundImage attribute.

Start by importing the desired image.

import sunsetImage from './sunset_background.jpg';

Then, set sunsetImage as the value for the backgroundImage attribute.

card: {
  backgroundImage: "url(" + sunsetImage + ")",
  backgroundSize: "cover"
},

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

Utilizing React Hook Form for Interactive Slider and User Input Controls

Whenever I move the Slider, I want to retrieve the same value as when I enter a new value in the Input field. However, the current setup is not functioning correctly. <StyledSlider {register(NAME ...

Modify the content of a post in the Gutenberg editor on Wordpress

Let me outline the steps I have taken so far: I have created multiple posts using Gutenberg, incorporating various types of blocks/elements I have also designed a page using Gutenberg One of the functionalities I added is a custom widget called "load-pos ...

List items with toggles should only respond to clicks within the toggle element and not outside it

I am currently using material-ui in my react project and I have a specific requirement. I want the toggle functionality to only work when the toggle element itself is clicked, not any other part of the list item. How can I achieve this? <List> & ...

Convert the nodejs undefined into bindings.js within an Electron project (and utilize better-sqlite3)

My Electron.js project setup includes the following steps: Installing node 14 Installing vue-cli Creating a template project in Vue with: vue create myproject Adding an Electron wrapper like this: vue add electron builder Installing the better-sqlite3 lib ...

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Navigating the source-map-explorer tool in a ReactJs environment has left me feeling perplexed

I am facing an issue with my React project where the production build size of the main.xxxx.js file is too large (19.3 MB) and I need to reduce it. After researching online, I found out that analyzing the build files is the first step to identify the code ...

Tips on viewing class object values within the `useEffect` hook

App.js import React, { useRef, useEffect } from "react"; import Token from "./Token"; export default function App() { const tokenRef = useRef(new Token()); useEffect(() => { console.log("current index of token: ", ...

Tips for triggering a sound only when transitioning from a true to false value for the first time

I have data for individuals that includes a dynamically changing boolean value. This value can be true or false, and it updates automatically. The webpage fetches the data every 5 seconds and displays it. If the value for any person is false, a sound is p ...

The @urql/exchange-auth module does not include the token in the header when making requests

I am currently utilizing the urql GraphQL client in my project. However, I have encountered an issue where the authorization token is not automatically added to the header after logging in. In order to set the token in the header, I have to refresh the pag ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Issues with React's useState hook not updating properly

As a React beginner, I am facing an issue with my input field filtering functionality. The problem arises when the results are filtered and rendered, as it seems to be ignoring the last character of the input value. For instance: If I type in "s", nothing ...

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

What is the best way to send root parameters within the resolver function of a nested query?

I have a question regarding the structure of my GraphQL queries Category1(name: $cat1){ Category2(secondName: $cat2){ secondName }} This is how my schema is set up: const Query = new GraphQLObjectType({ name: 'Query', fields: { ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...

Reasons for the failure of file uploads from the React frontend to the backend system

Recently, I embarked on a new project that involves using React for the front-end and Node for the back-end. The main requirement of this project is to upload multiple images from the front-end, with the back-end handling the file uploads to Cloudinary. I ...

What is the most effective method for updating edited rows in a DataGrid MUI and transferring them to

Is there a way to update the values I just edited in firebase after using editRow (please correct me if I'm mistaken)? Within DataGrid //Enable row edit mode editMode="row" //Any updates made in the row are stored in this variable, overrid ...

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

Having trouble adding a package right after creating a project with create-react-app

Just started learning react (only a day ago). Used create-react-app command line to set up an app. Here's what I did: create-react-app my-app npm start App was running smoothly at this point. Then, I proceeded with: npm install youtube-api-search n ...

Can't decide between using tabs or back buttons to navigate with react-navigation stack/bottomTab navigator? Here's a step-by

I have developed a unique react native application that currently does not incorporate any form of navigation. However, I am now interested in implementing the powerful functionality offered by react-navigation. Unfortunately, I am encountering difficultie ...