LeoL
LeoL

Reputation: 13

ReactJS not displaying backgroundImage inline CSS

I'm trying to create a component that renders images as "tiles" or "cards" using inline CSS with ReactJS. However, I cannot figure out why the image is not displaying. I'm new to ReactJS, so this might be simply a dependency package I haven't installed - but please advise!

I bootstrapped this project from Create-React-App.

I've checked URL configuration, inline CSS syntax, and inspected the page on my local server, but I can't seem to figure out why the image won't display. I've tried to add "require" around the url, but that didn't seem to work (unless there is a specific way I need to set a url to be required?). I've also tried to use the image tag instead, having but that displayed the tiny default image icon when the actual image fails to load.

import React from 'react';

function getUrl(name) {
  let string = `./images/${name}.jpg`;
  return string
}

function HorizontalTile(props) {

  let name = props.name;
  let position = props.position;
  let size = props.size;

  let url = getUrl(name);

  const divstyle = {
    height: "50vh",
    width: "100%",
    backgroundImage: `url(${url})`,
    backgroundPosition: `${position}`,
    backgroundSize: `${size}`,
    backgroundRepeat: "no-repeat",
    WebkitTransition: "all",
    msTransition: "all",
  };

  return (
    <div style={divstyle} alt={name}></div>
  )
}


export default HorizontalTile

I'm calling this component like this, in another JS file within the same directory: . . .

import HorizontalTile from './HorizontalTile';
.
.
.
<HorizontalTile name="proj-hor-1" position="center" size="cover" />
.
.
.
export default Photos

The spacing loads fine and all the CSS elements seem to be captured, but the image doesn't appear. Any idea what I can try?

Upvotes: 0

Views: 207

Answers (2)

sdkcy
sdkcy

Reputation: 3548

You need to require your images like this,

function getUrl(name) {
  let string = require(`./images/${name}.jpg`);
  return string
}

in this function, string variable is redundant. So you can return require directly.

Why the problem is resolved with require?

If we want to use without require(like in your question), we need to place our assets(images) to output directory(which is defined in your bundler(webpack) configuration). If you move your images to your output directory, your code should work.

But in the big projects, commonly we use file-loader or url-loder for our assets file. So if you use file-loader or url-loader, you should use require for importing static images.

Images(with require) are resolved like JS modules are resolved.

Upvotes: 1

Ronald Paredes
Ronald Paredes

Reputation: 1

Where is your images folder? Make sure your images folder is inside the public folder and not the src folder.

root
├── public
│   └── images
└── src
    └── index.js

Upvotes: 0

Related Questions