Skip to main content

3.25 Working With Inline Styles

There is nothing wrong with using css files and classes, and it might even be the preferred way, but what you also often see in react apps is that you actually design your styles in JavaScript.

CSS-in-JS

Let's make a variable style, to be precise the constant:

App.js
...
render() {
const style = { // object
backgroundColor: 'white',
font: 'inherit',
border: '1px solid blue',
padding: '8px',
cursor: 'pointer',
}

return (
<div className="App">
<h1>Hi, I'm a React app!</h1>
<p>This is really working!</p>
<button style={style} onClick={() => this.switchNameHandler('MAx')}>
Switch Name
</button>
...

The style constant it's not a css class property is an object. Label -> value. Value is a string. Is always. Because it's JavaScript. As you can see, the css style properties have JavaScript representations. In camelCase:

background-color -> backgroundColor
caution

In JavaScript, kebab-case doesn't fit because of syntax rule. - is not allowed in identifier so padding-top is not valid for variable or property name. stackoverflow.com

You can't wrap kebab-case form in quotes:

'background-color': 'white' // error

Read more about React structure stackoverflow.com

See docs on styling here reactjs.org and see FAQ: Styling and CSS reactjs.org