I am trying to add Image dynamically in jsx-react but it won't show up

Viewed 70
import React from "react";
import ReactDOM from "react-dom";

var bImg = prompt("Which image do you want to set as background image?");
const bStyle = {
  backgroundImage: "url(bImg)" // i stored the link here 
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <div style={bStyle}> // I stored it here but still it won't show up
    <h1>Hello world!!</h1>
  </div>,
  rootElement
);

The rest works fine, but the background image won't load up from the URL I input in the prompt. The error shows that 'bImg' is assigned a value, but it is not used.

1 Answers

Output:

enter image description here

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

var bImg = prompt("Which image do you want to set as background image?");
const bStyle = {
  backgroundImage: `url(${bImg})` // i stored the link here
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <div style={bStyle}>
    // I stored it here but still it won't show up
    <h1>Hello world!!</h1>
  </div>,
  rootElement
);

StackBlitz Demo

Related