I have a div that has a decently long list of styles that would look ridiculous to apply inline, however, the div takes a parameter of a background image url that will change upon updating state.
Styled inline, my element looks like this:
      <div style={{width: 55,
                  height: 55,
                  position: 'fixed',
                  borderRadius: '50%',
                  bottom: 130,
                  zIndex: 200,
                  backgroundImage: `url(${this.state.avatar})`}}>
However, when I do this, my background image disappears completely:
<div className="avatar" style={{backgroundImage: `url(${this.state.avatar})`}}>
What is the fix here?
I created a sample project with create-react-app and used the following code, it's working for me:
App.js:
import React, {Component} from 'react';
import './App.css';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {avatar: 'https://www.gstatic.com/webp/gallery3/1.png'}
  }
  render() {
    return (
      <div className="avatar" style={{backgroundImage: `url(${this.state.avatar})`}}>
        something here...
      </div>
    );
  }
}
export default App;
And the App.css:
.avatar {
  width: 500px;
  height: 500px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
}
                        @salman.zare 's answer is 100% correct to the question I had posted, however, the problem I had turned out not to have anything to do with combining a className and an inline style. The issue was that my div container was too small for the image, 50px. Here is was I added to make it work: background-size: contain;
So:
.avatar {
  width: 50px;
  height: 50px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
  background-size: contain;
}
This also works and will not cut-off the bottom of the image if using no-repeat: background-size: 100% 100%;
.avatar {
  width: 55px;
  height: 55px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With