简体   繁体   中英

How to set the background image for a div in React?

I'm creating a react application, and I have a component that is define more or less like this:

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 => {
          _this.setState({
            data: result.data,
            loading: false,
            error: null
          });
        })
        .catch(err => {
          _this.setState({
            loading: false,
            error: err
          });
        });
  }

  componentWillUnmount() {
    this.serverRequest.abort();
  }

  renderLoading() {
    return <div>Loading...</div>
  }

  renderError() {
    return (
      <div>
        Something when wrong: {this.state.error.message}
      </div>
    );
  }

  renderData() {
    const { error, data} = this.state;

    if (error) {
      return this.renderError();
    }

    return (
      <div>
        {data.map(d=> {
          if (d.imageUrl) {
            <div className="dataDiv" style="background: url('{d.imageUrl}')" key={d.Id}>{d.name}</div>
          } else {
            <div className="dataDiv" style="background: url('LinkToSomeImage')" key={d.Id}>{d.name}</div>
          }
        }
        )}
      </div>
    )
  }

  render() {
    return (
      <div className="App">
        {this.props.loading ? this.renderLoading() : this.renderData()}
      </div>
    );
  }
}

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 dataDiv class, which is define inside my App.css 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 imageUrl 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 renderData function. How can I fix this code, or is there any way to handle this more gracefully, probably maybe inside the CSS?

I would do like this Please make sure to check backgroundUrl equal to your desired CSS.

 {data.map(d => { let backgroundUrl = "LinkToSomeImage"; if (d.imageUrl) { backgroundUrl = d.imageUrl; } return ( <div className="dataDiv" style={{backgroundImage: `url(${backgroundUrl})`}} key={d.Id}>{d.name}</div> ) })}

EDIT

A full function would be:

 renderData() { const { error, data} = this.state; if (error) { return this.renderError(); } return ( <div> {data.map(d => { let backgroundUrl = "LinkToSomeImage"; if (d.imageUrl) { backgroundUrl = d.imageUrl; } return ( <div className="dataDiv" style={{backgroundImage: `url(${backgroundUrl})`}} key={d.Id}>{d.name}</div> ) })} </div> ) }

          <Box
            onClick={() => {
              history.push({
                pathname: `/p/c/${data.ProductName.replace(/\//g, "~")}/1`
              });
            }}
            css={{
              backgroundImage:`url(${data.imageUrl||"/default-placeholder.png"})`,
              backgroundPosition: 'center',
              backgroundRepeat: 'no-repeat'
            }}
          >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM