user3590911 user3590911 - 1 month ago 12
Javascript Question

React inline styles error

Big fan of inline styles and decided to give it a try. I'm slowly getting the hang of it but I'm now stuck because I keep getting the "Unknown prop

styles
on tag" error.

My code is as shown below:

render(){
let imgUrl = 'http://mrmrs.io/images/0006.jpg';
let divStyles = {
backgroundImage:'url(" + imgUrl + ")',
backgroundSize: 'cover'
};
return(
<main class="cf w-100">
<div class="fl w-50 w-third-m w-25-ns">
<div class="aspect-ratio aspect-ratio--1x1">
<img styles="{{divStyles}}" class="db bg-center cover aspect-ratio--object" />
</div>
</div>
</main>

)
}


The simple stuff are always the ones that give me the most problems. Any help would be appreciated.

Answer

The prop should be style not styles. And you need to define a height and a width to the img tag.

Hope this helps!

class App extends React.Component{
  render(){
      let imgUrl = 'http://mrmrs.io/images/0006.jpg';
      let divStyles = {
          backgroundImage:'url(' + imgUrl + ')',
          backgroundSize: 'cover',
          height: 200,
          width: 200,
      };
      return(
          <main className="cf w-100">
            <div className="fl w-50 w-third-m w-25-ns">
              <div className="aspect-ratio aspect-ratio--1x1">
                <img style={divStyles}  className="db bg-center cover aspect-ratio--object" />
              </div>
            </div>
          </main>

      )
  }
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Comments