JSX gives us the convenience of combining HTML syntax and JavaScript under one file in React. However, our stylesheets always existed in a separate directory. With inline styles, you have to option to combine CSS syntax with JSX code.

Syntax

Let’s say that we wanted to build a yellow square.

import React from 'react' function ColorBlock() {

let styles = {

margin: '20px',

width: '250px',

height: '250px',

backgroundColor: 'yellow',

}; return (

<div>

<div className="yellow-box" style={styles}>

</div>

</div>

)

} export default ColorBlock

You’ll notice a couple of things.

- The CSS attributes and values are stored in an object. Therefore, you must use comma’s instead of semi-colons to separate your declarations.

- Attribute names are in camelCase instead of using hyphens.

Now what if you wanted to build another box with different values?

import React from 'react' function ColorBlock() {

var styles1 = {

margin: '20px',

width: '250px',

height: '250px',

backgroundColor: 'yellow',

display: 'inline-block',

}; var styles2 = {

margin: '20px',

width: '200px',

height: '200px',

backgroundColor: 'blue',

display: 'inline-block',

}; return (

<div>

<div className="square-box" style={styles1}>

</div>

<div className="square-box" style={styles2}>

</div>

</div>

)

} export default ColorBlock

Why would anyone want to do this? It makes more sense to just have separate stylesheets.

What if you wanted to generate a random color? I can’t think of a way to generate random colors in CSS (or at least that I’m aware of). But I would know how to do that in JavaScript.

Math.random()

JavaScript gives us a wonderful method called Math.random() .

Math.random()

=> 0.8535371342594502

Math.floor(Math.random() * 10)

=> random number (0 - 9)

RGB (Red Green Blue) color

These three colors are added together in various ways to reproduce a broad array of colors. The RGB range for each color is from 0 to 255.

255 * 255 * 255 = 16,777,216 different possible colors.

#p1 {color: rgb(255, 0, 0);} /* red */

#p2 {color: rgb(0, 255, 0);} /* green */

#p3 {color: rgb(0, 0, 255);} /* blue */

Now let’s implement all this in React.

import React from 'react' function ColorBlock() {

let rgb = [] for (var i = 0; i < 3; i++) {

let r = Math.floor(Math.random() * 256)

rgb.push(r)

} var styles = {

margin: '20px',

width: '250px',

height: '250px',

backgroundColor: `rgb(${rgb})`,

display: 'inline-block',

}; return (

<div>

<div className="square-box" style={styles}>

</div>

</div>

)

} export default ColorBlock

First Render

Second Render

Third Render

So React styles: Yay or Nay?

There’s a lot of talk of whether inline styles should be used or not and many argued that it’s bad practice. In my opinion, I would say that it should be used only when necessary especially when some JavaScript logic is required. I can’t imagine the many lines of CSS code on top of the JSX code. I recommending this blog to weigh in the pro’s and con’s.