How to apply CSS inline styles in React?

In React, you use style prop to apply inline styles. The value to the style prop is an object of CSS properties and their values like this style={{property1:value, property2:value, ...propertyn:value}}.

On the other hand, in HTML, you apply inline style like this: style="property1:value; property2:value; ...propertyn:value;"

Note: In React, instead of a semicolon, you use a comma to separate more than one CSS property.

It is important to note that you convert CSS properties to a camel case when you apply an inline style to an element. In simple terms, you change all multi-word CSS properties to a camel case while applying the inline style. You remove dashes from the CSS property name and then change the first letter of each word to capital except for the first word. Following are some examples of CSS properties converted to camel case:

CSS Property camel-cased CSS Property
box-shadow boxShadow
font-size fontSize
background-color backgroundColor
border-bottom-width borderBottomWidth
padding-left paddingLeft

This is how you convert CSS property to camel case.

App.js
import React from 'react';

let styles = {
  fontSize: '30px',
  color: 'red',
  border: '3px solid #aaa',
  marginTop: '20px',
};

export default function App() {
  return (
    <div>
      <h1 style={{ backgroundColor: 'red', paddingBottom: '10px', color: '#444' }}>Hello World</h1>
      <h1 style={styles}>Good Morning</h1>
    </div>
  );
}

Output

inline styling in React

Here, two different ways of setting inline styles in React are shown.

1. CSS styles are directly set on the element.

App.js
import React from 'react';

export default function App() {
  return (
    <div>
      <h1 style={{ backgroundColor: 'red', paddingBottom: '10px', color: '#444' }}>Hello World</h1>
    </div>
  );
}

2. Styles object is assigned to a variable and then the value of the style prop is set to that variable.

App.js
import React from 'react';

let styles = {
  fontSize: '30px',
  color: 'red',
  border: '3px solid #aaa',
  marginTop: '20px',
};

export default function App() {
  return (
    <div>
      <h1 style={styles}>Good Morning</h1>
    </div>
  );
}

Recommended Posts