Currently working on toggling the CSS background image within this React application. The images have been successfully imported and a variable called "image" is set to the imported image as the iteration increases/decreases with each click.
The issue I'm encountering is that the body background image does not update accordingly. My understanding was that the background image should refresh in the componentDidUpdate method, as the iterative buttons toggle setState which triggers a re-render.
import Background1 from "../images/bg/1.png";
import Background2 from "../images/bg/3.png";
import Background3 from "../images/bg/4.png";
class UserPreferences extends Component {
constructor(props) {
super(props);
this.state = {
backgroundNumber: 1
};
}
buttonNumberCalcPlus = () => {
this.setState({ backgroundNumber: ++this.state.backgroundNumber });
};
buttonNumberCalcMinus = () => {
this.setState({ backgroundNumber: --this.state.backgroundNumber });
};
componentDidUpdate() {
var currentBackground = "Background" + this.state.backgroundNumber;
console.log(currentBackground);
var image;
if (this.state.backgroundNumber == 1) {
image = Background1;
} else if (this.state.backgroundNumber == 2) {
image = Background2;
} else {
image = Background3;
}
var mainBg = {
backgroundImage: "url( " + { image } + ")"
};
console.log(mainBg);
document.body.style = { mainBg };
}
render() {
return (
<div>
<MainMenuToolbar />
<h2 className="texttimezonepref">Update background image.</h2>
<button
id="next"
onClick={this.buttonNumberCalcPlus}
className="addbutton"
>
NEXT
</button>
<button
id="prev"
onClick={this.buttonNumberCalcMinus}
className="subtractbutton"
>
PREV
</button>
</div>
);
}
}
Questioning whether this approach to changing the background in componentDidUpdate is correct:
var mainBg = {
backgroundImage: "url( " + { image } + ")"
};
document.body.style = { mainBg };