0

In my React project (made using create-react-app), I have an array of objects with the following format:

items : [{
    id:"test",
    title:"Test title",
    project_url:"/project/test",
    doc:"2018",
    description:"test description",
    link:"example.com",
    background_img:"../../../s.png",
    color:"#333333"
}]

I map these objects into elements to be displayed on the page:

_generateItems() {
    return this.state.items.map((item) => {
        return (
            <div className="item">
            <h3>{item.title}</h3>
            <div className="device" style={{backgroundImage:`url(${item.background_img})`}}/>
            <Link to={item.project_url}><div className="info_btn"><h6>More info</h6></div></Link>
            </div>
        )
    })
}

My problem is that I cannot get background image of the inner div to work. After scouring the internet, I tried to use template literals like so:

`url(${item.background_img})`

This allowed the project to compile and run without errors, and inspecting the div in the browser, I can see that it has the correct style. The image however does not appear on the div.

I am guessing it has to do with the way webpack handles static resources like images when it builds the project. How can I make it work?

1
  • it may be that the url ../../../filename (which is relative) is not relative to the page you are on nor the css url. Can you switch the urls to absolute urls? /path/to/file (be aware of the leading /) ? Commented Aug 23, 2018 at 20:55

1 Answer 1

1

Are your images served statically? If so, you should have a Public folder in your project's root directory (seeing that you have used create-react-app to set up your project).

Place your images (ie s.png) in the Public directory of your project, and then revise your code as follows:

items : [{
    id:"test",
    title:"Test title",
    project_url:"/project/test",
    doc:"2018",
    description:"test description",
    link:"example.com",
    background_img:"/s.png", // Update the image path  
    color:"#333333"
}]
Sign up to request clarification or add additional context in comments.

3 Comments

This worked right away. However I'd also like to know if its possible to have webpack handle them, like one would with a predetermined path (var img = require("/path/to/image"))
Great to hear that it worked - that is possible however I'm not sure why you would want to do that? In any case this might help you with that: stackoverflow.com/questions/31241734/… If you've found the answer above helpful please consider accepting :-)
Of course, I was just waiting for the timeout. I'll take a look at the linked thread. Thanks for the help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.