最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't load a local background image in ReactJS - Stack Overflow

programmeradmin5浏览0评论

I'm having some problems taking an image from my local machine with my React App.

I'm trying to take image like

style={{ backgroundImage: `url(../../assets/images/games/${img}))`  }}

But it's not working, and I don't understand why.

My file is located in

C:\Users\Me\Desktop\myreactapp\src\routes\GameSlider\index.js

And my images are in

 C:\Users\Me\Desktop\myreactapp\src\assets\images\games

This is how my index.js looks now (without imports):

const GameSlider = ( { key, id,  name, img, minPrice, maxSlots } ) => {
    return (
        <div key={key}>
            <div className="home-games">
                <div className="img" style={{ backgroundImage: `url(../../assets/images/games/${img}))`  }} alt="..." />
                <div className="price">
                    <IntlMessages id="gameSlider.startingAt" />
                    <p>
                        <span className="min">{minPrice}</span> 
                        <span className="per-slot">
                            <IntlMessages id="gameSlider.perSlot" />
                        </span>
                    </p>
                </div>
                <span className="title">{name}</span>
                <div className="features">
                    <Col span={24} className="feature">
                        <Icon type="lock" /> <IntlMessages id="gameSlider.upTo" /> {maxSlots} <IntlMessages id="general.slots" />
                    </Col>
                </div>
                <Link to={`/order/${id}`}><Button className="et-buy-button" style={{ background: 'rgb(241,89,89)', borderRadius: '20px' }}>BUY NOW!</Button></Link>
            </div>
        </div> 
    );
}

export default GameSlider;

I'm having some problems taking an image from my local machine with my React App.

I'm trying to take image like

style={{ backgroundImage: `url(../../assets/images/games/${img}))`  }}

But it's not working, and I don't understand why.

My file is located in

C:\Users\Me\Desktop\myreactapp\src\routes\GameSlider\index.js

And my images are in

 C:\Users\Me\Desktop\myreactapp\src\assets\images\games

This is how my index.js looks now (without imports):

const GameSlider = ( { key, id,  name, img, minPrice, maxSlots } ) => {
    return (
        <div key={key}>
            <div className="home-games">
                <div className="img" style={{ backgroundImage: `url(../../assets/images/games/${img}))`  }} alt="..." />
                <div className="price">
                    <IntlMessages id="gameSlider.startingAt" />
                    <p>
                        <span className="min">{minPrice}</span> 
                        <span className="per-slot">
                            <IntlMessages id="gameSlider.perSlot" />
                        </span>
                    </p>
                </div>
                <span className="title">{name}</span>
                <div className="features">
                    <Col span={24} className="feature">
                        <Icon type="lock" /> <IntlMessages id="gameSlider.upTo" /> {maxSlots} <IntlMessages id="general.slots" />
                    </Col>
                </div>
                <Link to={`/order/${id}`}><Button className="et-buy-button" style={{ background: 'rgb(241,89,89)', borderRadius: '20px' }}>BUY NOW!</Button></Link>
            </div>
        </div> 
    );
}

export default GameSlider;
Share Improve this question edited Feb 29, 2020 at 8:48 Kate Orlova 3,2835 gold badges14 silver badges36 bronze badges asked Feb 29, 2020 at 4:27 FeruumomasterFeruumomaster 731 gold badge2 silver badges8 bronze badges 10
  • The url in your question should work, but the url in your code block is wrong, have you tried updating the url in the style tag to be: url(../../assets/images/games/${img}))? – JoshuaCWebDeveloper Commented Feb 29, 2020 at 4:29
  • Yes I can see that, but now is just like in full code (index.js), but still don't work – Feruumomaster Commented Feb 29, 2020 at 4:30
  • Have you tried debugging this in the DevTools of your browser (I prefer Chrome DevTools)? Doing that, you would be able to check and see if the puted url is correct (i.e. what is the value of img?) and whether or not your browser is able to resolve the url. – JoshuaCWebDeveloper Commented Feb 29, 2020 at 4:32
  • Yes when I inspect element on image it gives me " background-image: url("../../assets/images/games/cs16.jpg"); " this image is in that folder – Feruumomaster Commented Feb 29, 2020 at 4:35
  • are u using plain node.js or with any package? – Aoudesh01 Commented Feb 29, 2020 at 4:37
 |  Show 5 more ments

4 Answers 4

Reset to default 8

1 - Import your img:

import img from '../../pics/asteroids.jpg'

2 - And then use it:

<div style={{backgroundImage: `url(${img})`}}>Test</div>

On your page this div will look like this:

<div style="background-image: url(&quot;/static/media/asteroids.c8ab11b3.jpg&quot;);">Test</div>

Absolute path and relative path is always one of the issue for developers to fix :P so there is a another way to solve this easily.

You can use something like this:

import the whatever image in the namespace

import backgroundImg from '../images/BackgroundImage.jpg';

then use it the element like this

 <img src={backgroundImg} />

let me know if this works.

If you want to use image or images without importing them, you should put your assets folder into the public folder and use them like below:

src='/assets/images/pic.jpeg'

I tried for hours lots of different solutions and in the end it came down to having quotes inside the url call, like this:

    `url('${ImportedImage}')`

Quite weird that this happened though because in previous projects it has always worked fine without the inner quotes (actually, I've noticed in the past that it worked with OR without the quotes). Only thing I've done differently this time is used the TypeScript template of create-react-app to set up the project.

发布评论

评论列表(0)

  1. 暂无评论