Generating inline font-size style using ReactJS
Asked Answered
M

3

47

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!

Myall answered 5/11, 2014 at 14:38 Comment(3)
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.Cleromancy
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 correctlyMyall
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!Aglow
M
88

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 :)

Myall answered 5/11, 2014 at 14:57 Comment(3)
And if you have something like: -webkit-box-shadow, then just put webkitBoxShadowDol
@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. facebook.github.io/react/tips/inline-styles.htmlEck
the link in the answer is no longer availableEgis
R
1

I use fontSize: pixels numbers

Retractile answered 30/9, 2016 at 19:15 Comment(0)
P
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!

Pinckney answered 28/11, 2018 at 8:36 Comment(2)
You are confusing HTML attributes like aria-label and data-*, [casing-docs]( reactjs.org/docs/dom-elements.html) and CSS properties created with inline styles like backgroundColor and WebkitTransition reactjs.org/docs/dom-elements.html#styleOxy
There is nothing to get confuse, instead-of background-color need to use backgroundColor. It is so simple.Pinckney

© 2022 - 2024 — McMap. All rights reserved.