How to write inline CSS in JSX?

How to use JSX in React.js? »

Up until now, you’ve written plain JSX code (that looks like HTML but is not). None of the code you wrote so far included any sort of styling. Now, let’s try to add some styles to our content, so that index.js looks like:

// Import Libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Create React Component and add some styles to it
const App = function() {
return 
<div>

<h1 style ="color:red" >
Hello there!
</h1>

 I am a paragraph. 

</div>;
};

// Show React Component on the browser

ReactDOM.render(
<App/>,
document.querySelector('#root')
);

As soon as you save the above index.js file, you’ll run into an error that looks something like this in your web browser:

The `style` prop expects a mapping from style properties to values, not a string. 
For example, style={{marginRight: spacing + 'em'}} when using JSX.

in h1 (at src/index.js:9)

in div (at src/index.js:8)

in App (at src/index.js:19)

It is because, although JSX looks like HTML, internally it is not. Therefore, the method of adding styles to JSX is a bit different from those of CSS (inline) in HTML. In fact, the way of adding a class to an element in JSX is also different. In short, here I’m going to mention different ways to use inline CSS in the JSX code:

Leave a Comment