title: How to set the background image for a div in React?
body: <p>I'm creating a react application, and I have a component that is define more or less like this:</p>
  
  <pre><code>import React, { Component } from 'react';
  import axios from 'axios';
  import './App.css';
  
  class App extends Component {
    constructor(props) {
      super(props);
  
      this.state = {
        data: [],
        loading: true,
        error: null
      };
    }
  
    componentDidMount() {
      var _this = this;
      this.serverRequest = 
        axios
          .get("LinkToAPI")
          .then(result =&gt; {
            _this.setState({
              data: result.data,
              loading: false,
              error: null
            });
          })
          .catch(err =&gt; {
            _this.setState({
              loading: false,
              error: err
            });
          });
    }
  
    componentWillUnmount() {
      this.serverRequest.abort();
    }
  
    renderLoading() {
      return &lt;div&gt;Loading...&lt;/div&gt;
    }
  
    renderError() {
      return (
        &lt;div&gt;
          Something when wrong: {this.state.error.message}
        &lt;/div&gt;
      );
    }
  
    renderData() {
      const { error, data} = this.state;
  
      if (error) {
        return this.renderError();
      }
  
      return (
        &lt;div&gt;
          {data.map(d=&gt; {
            if (d.imageUrl) {
              &lt;div className="dataDiv" style="background: url('{d.imageUrl}')" key={d.Id}&gt;{d.name}&lt;/div&gt;
            } else {
              &lt;div className="dataDiv" style="background: url('LinkToSomeImage')" key={d.Id}&gt;{d.name}&lt;/div&gt;
            }
          }
          )}
        &lt;/div&gt;
      )
    }
  
    render() {
      return (
        &lt;div className="App"&gt;
          {this.props.loading ? this.renderLoading() : this.renderData()}
        &lt;/div&gt;
      );
    }
  }
  </code></pre>
  
  <p>It basically gets the JSON data from the API, and using it renders some divs with the data inside the JSON. I'm applying to the divs containing the data <code>dataDiv</code> class, which is define inside my <code>App.css</code> file. Additionally, I want to set a background image for the div. What exactly I want to do is that if the data entry includes a field named <code>imageUrl</code> I want to use that url as a url to the background image, otherwise, if it is null or empty, I want to use a default url that I found from the internet. What is a proper way to handle this in React? The code segment above doesn't seem to work, especially the if-else statement inside the <code>renderData</code> function. How can I fix this code, or is there any way to handle this more gracefully, probably maybe inside the CSS?</p>