chrisrhyno2003
chrisrhyno2003

Reputation: 4177

React specifying inline styles

I am trying to specify inline styles for my react component something this way:

var style = {
    border-left: 1px solid #222,
    color: #FFFF,
    float: 'right',
    font-size: 14px
}

<div id="myDiv" style={style}> </div>

My linter keeps throwing me an error saying unexpected token on line 3 - that is border-left: 1px solid #222.

What am I doing wrong? Or how's the way to set styles?

Thanks

Upvotes: 3

Views: 7327

Answers (2)

B4BIPIN
B4BIPIN

Reputation: 353

When you pass an object to a style property of HTML's element, keys should have upper camelCase and values must have a string type in an object. for example:-

var myStyle = {
    borderLeft: '1px solid #222',
    color: '#FFFF',
    float: 'right',
    fontSize: '14px'
}
<div id="myDiv" style={myStyle}></div>

Upvotes: 0

Vincas Stonys
Vincas Stonys

Reputation: 1135

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string

You have multiple errors here it seems:

  • First, the marked line is wrong, because border-left should be borderLeft
  • 1px solid #222 should be in quotes I believe, as should every property value, i.e. color, font size
  • font-size, the same as border-left should be fontSize
  • you might also want to use const instead of var, if you use ES6

Reference here: https://facebook.github.io/react/tips/inline-styles.html

Upvotes: 3

Related Questions