Home » Inline Style in React

Inline Style in React

by Online Tutorials Library

Inline Style in React

Introduction

In frontend projects that rarely require a single-page app, inline styles of DOM elements are often placed in the target element’s style=”property: value” attribute.

But in React, things are quite different regarding styling inline. This guide focuses on achieving this using a real-world example of creating a User Profile Card component.

Styling Components in React

You may already be aware of the regular way to style React components using the classname attribute in conjunction with an external stylesheet:

jsx

CSS

Inline Styles

Getting the same result with inline styles works quite differently. To use inline styles in React, use the style attribute, which accepts a JavaScript object with camel properties. Example:

Note that padding value does not have a unit because React adds a ‘px‘ suffix to some numeric inline style properties. In cases where you need to use other units, such as ’em’ or ‘rem’, explicitly specify the unit with the value as a string. Applying this to the padding property should be padding: ‘1.5em’.

Also, these styles are not automatically vendor-prefixed, so you have to add vendor prefixes manually.

Improve Readability

The readability of MyComponent drops dramatically if the styles become too many and everything gets clunky. As shown below, since styles are just objects, they can be removed from the component.

jsx

Building a Card Component

Let’s build the user card component.

Rule of Thumb

The official React documentation barks at using inline styling as the primary means of styling projects and recommends using the className attribute instead.

Note Some examples in the documentation use a style for convenience, but it is generally not recommended to use the style attribute as the primary means of styling elements.

In most cases, class names should refer to classes defined in an external CSS stylesheet. Styles are often used in React apps to add dynamically computed styles at render time.


Next TopicjQuery vs. React

You may also like