45

I am trying to do something like this in ReactJS:

var MyReactClass = React.createClass({
    render: function() {
        var myDivText = "Hello!";
        var myFontSize = 6; //this is actually something more complicated, I'm calculating it on the fly
        var divStyle = {
            font-size: {fontSize + 'px !important;'},
        };
        return (<div style={divStyle}>{myDivText}</div>);
   }
});

The problem is that I get this error when I run my code: "Module build failed: Error: Parse Error: Line 5: Unexpected token -" apparently, React doesn't like that font-size has a dash in it. How do I get around this? Is there some way to escape that character for react? Is there some different css property that react likes better that does the same thing?

Thanks!

kat
  • 5,645
  • 4
  • 19
  • 35
  • It’s actually JavaScript that throws the error first. An unquoted property name must be a *valid identifier name* or *numeric literal*. Valid code would be: `{'font-size': '10px'}` (with quotes). Allthough I’m not sure how React would handle it. – David Hellsing Nov 05 '14 at 15:18
  • It's true that JavaScript has those restrictions on unquoted property names, but this is actually a key in a React style object, not a javascript property, if I understand correctly – kat Nov 06 '14 at 15:36
  • camelCase works inline, and non-camel stylings work in stylesheets. Stylesheets are a common best practice so others don't have to worry about missing anything in a dense code block. Glad you figured it out though! – Jake Acosta Aug 21 '18 at 19:55

3 Answers3

87

Use fontSize instead of font-size

the solution is to camelCase properties which usually contain a dash

http://facebook.github.io/react/tips/inline-styles.html

Answered my own question :)

kat
  • 5,645
  • 4
  • 19
  • 35
  • 1
    And if you have something like: -webkit-box-shadow, then just put webkitBoxShadow – Andy B Feb 27 '15 at 14:05
  • 8
    @AndyB You need to actually start that with a capital W so it would be "WebkitBoxShadow". React states vendor prefixes other than ms start with a capital. https://facebook.github.io/react/tips/inline-styles.html – bradcush Sep 18 '15 at 20:55
1

I use fontSize: pixels numbers

0

As https://reactjs.org/docs/dom-elements.html says,
We need to remove '-' and upperCase except first word

Example-
background-color as backgroundColor,

Same will be applicable everywhere except a few as-

aria-* and data-*

example-

aria-label as aria-label 

Above worked for me!

S.Yadav
  • 4,273
  • 3
  • 37
  • 44
  • You are confusing HTML attributes like aria-label and data-*, [casing-docs]( https://reactjs.org/docs/dom-elements.html) and CSS properties created with inline styles like backgroundColor and WebkitTransition https://reactjs.org/docs/dom-elements.html#style – Arye Eidelman Sep 08 '19 at 15:19
  • There is nothing to get confuse, instead-of background-color need to use backgroundColor. It is so simple. – S.Yadav Sep 09 '19 at 05:15