1

I want to change the background based on the time of the day. So I get this function in js, as CSS cannot use conditional logic. But it is not working, and it seems that the url is not right.

I have tried "URL('path')", and it is not working in react. How chould I change the background image in react?

[![enter image description here][1]][1]

import { getTheme } from "../models/themes.ts"
import day from "../assets/images/gallaxyDay.png"
import night from "../assets/images/gallaxy.jpeg"

// fixme: this is not working, still cannot find why
export function getBackgroundStyles() {
    if (getTheme() == "day") {
        return {
            "backgroundRepeat": "repeat",
            "backgroundImage": "url(" + { day } + ")"
        }
    }
    return {
        "backgroundRepeat": "repeat",
        "backgroundImage": `url(${night})`
    }
}
    class Hall extends React.Component {
        render() {
            let styles = getBackgroundStyles()
            return <div className="hall">
                <Sidebar style={{ styles }} />
                <Feeds />
                <Creation></Creation>
            </div>
        }
    }


  [1]: https://i.stack.imgur.com/8FPfr.png
maki
  • 477
  • 2
  • 12
  • You could use sass. Have you tried to write a conditional check on it – Pranavjeet.Mishra Jan 10 '22 at 10:18
  • Does this answer your question? [Setting a backgroundImage With React Inline Styles](https://stackoverflow.com/questions/39195687/setting-a-backgroundimage-with-react-inline-styles) – Terry Jan 10 '22 at 10:39
  • The syntax you're using to set the `backgroundImage` is incorrect: you need to follow the `url(...)` format, i.e. https://stackoverflow.com/questions/39195687/setting-a-backgroundimage-with-react-inline-styles – Terry Jan 10 '22 at 10:39
  • I have tried with url(...), and is still not working. – maki Jan 10 '22 at 15:23

1 Answers1

0

You could use getTheme() function for the background-style to determine the color value, as follows:

@function set-style($color) {
    @if (getTheme() == "day") {
      @return { backgroundRepeat: "repeat",
                backgroundImage: day}
    }
    @else {
       @return { backgroundRepeat: "repeat",
                backgroundImage: night}
    } }

Then use the above function as below:

div { set-style: // the style and whatever else }