DEV Community

Cover image for Styling React Components
Bipin Rajbhar
Bipin Rajbhar

Posted on • Edited on

Styling React Components

There are two primary ways to style a React Component.

  1. Inline CSS with style prop.
  2. External CSS with className prop.

style prop

In HTML you pass CSS as a String.

<p style="margin-top: 10; color: red;">Something went wrong.</p>
Enter fullscreen mode Exit fullscreen mode

In React, you have to pass CSS as a Object.

<p style={{marginTop: 10, color: "red"}}>Something went wrong.</p>
Enter fullscreen mode Exit fullscreen mode

In the React {{ and }} is actually a combination of JSX express and an Object express.

In React the property name of the style prop is camelCase instead of kebab-cased.

className prop

In HTML you apply a class name to an element using the class attribute.

<p class="error-message">Something went wrong.</p>
Enter fullscreen mode Exit fullscreen mode

In React you apply a class name to an element using the className attribute.

<p className="error-message">Something went wrong.</p>
Enter fullscreen mode Exit fullscreen mode

My name is Bipin Rajbhar and I am a software engineer at QuikieApps, and you can follow or connect to me on Twitter and Linked In

Resources
The Beginner's Guide to React
Epic React

Top comments (5)

Collapse
 
clarity89 profile image
Alex K. • Edited

Hi, I think you'd update your example and fix the quotes:

<p style={{marginTop: 10, color: "red"}}>Something went wrong.</p>
Enter fullscreen mode Exit fullscreen mode

The css styles that you pass to the rules need to be a string or number so instead of color: red it is color: "red".
Also I think the correct spelling is kebab-case ;)

Hope this helps!

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar • Edited

Thanks a lot πŸ˜….

Collapse
 
mkantz84 profile image
Michael Kantz

Nice article.
Though I do not think inline CSS is a primary way to style React component - it is not a recommended approach.
Also, you have more ways like css-in-js and css-modules.

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar

I am totally agree to you.

This article is for beginners 😊.

Collapse
 
ganeshh___ profile image
NGS Harsha

oh wow