0

I'm trying to change background image by accessing DOM and changing css property like so:

///anotherweathermap.js

const changePic = () => {
    document.getElementById('bckgAnother').style.backgroundImage = "url(../img/kaunas.jpg)";
}

The image will not load enter image description here but when I put the img path in css, the img path is different:

enter image description here
If I insert the same path, the one with static/media.., the DOM manipulation works. This is the order of files: enter image description here

1 Answer 1

1

Relative URLs in CSS images are computed between the location of the style sheet (which will be the URL of the webpage itself for inline CSS) and the URL of the image.

They have nothing to do with either:

  • The URL of the JS file
  • The location on the file system of the JS file
  • The location on the file system of the image (except in so far as that is used to determine the URL it gets)

Since you are using React, you will need to import the image and then use the imported value of it to get the URL.

You should change your logic to set the value based on state and avoid direct DOM manipulation.

import Default from '../img/default.jpg';
import Kaunas from '../img/kaunas.jpg';


const AnotherWeatherMap = (props) => {
    const [background, setBackground] = useState(Default);

    const css = {
        backgroundImage: `url(${background})`
    };

    return (<div style={css}>
        <button onClick={ () => setBackground(Kaunas) }>Change background<button>
    </div>);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I'll keep this in mind that React has a different approach with images.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.