Languages
[Edit]
EN

React - how to style

3 points
Created by:
chelsea
746

In this article, we would like to show you how to style elements in React.

There are two of the most common ways to style in React:

  1. by using inline styling object with style property,
  2. by using CSS style sheets with className property.

Note: the truth is there are more ways how to style e.g. styledComponents, etc. but in this article we present only simplest approaches.

1. Using inline styling object

In this solution we create const myComponentStyle for our style, then we need to attach it to MyComponent with style property.

// ONLINE-RUNNER:browser;

// import React from 'react'
// import ReactDOM from 'react'

const myComponentStyle = {
    height: '200px',
    width: '200px',
    background: 'goldenrod',
    textAlign: 'center'

}

const MyComponent = () => {
    return (
        <div style={myComponentStyle}>
            MyComponent
        </div>
    )
}

const root = document.querySelector('#root');
ReactDOM.render(<MyComponent/>, root );

Note: 
We use different syntax in inline styling than in CSS style sheets (camel case convention).

2. Using CSS style sheets

In this solution, we need to attach ./MyComponent.css file which contains my-component-style definition that will be used by MyComponent with className property.

MyComponent.jsx file:

import React from 'react'
import './MyComponent.css'

const MyComponent = () => {
    return (
        <div className="my-component-style">
            MyComponent
        </div>
    )
}

MyComponent.css file:

.my-component-style {
    width: 200px;
    height: 200px;
    background: goldenrod;
    text-align: center;
}

Browser output:

CSS styling example in React
CSS styling example in React
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - how to style
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join