Styling React JS Application

Introduction

This article will guide you on how to apply CSS style in React JS application. There are many ways to apply style but in this article we will take a closer look with,

  • Inline Style
  • CSS stylesheet

Inline Style

If we want to perform style for an element using inline style attribute, the value must be a JavaScript object type.

import './App.css'; 
function App() {
  return (
    <div>
      <h1 style={{color: "orange"}}>Welcome to rect js application</h1>
    </div>
  );
}
export default App;

Instead of color attribute we can apply any valid attribute of style with same way.

Styling React js application

Style using JavaScript Object

We can perform styling on element using JS object as well. Take a look in below example.

Create an object and add some style in that, later we can apply this object as style for an element.

Styling React js application

Code

import logo from './logo.svg';
import './App.css'; 
function App() {
  const objectStyle = {
    color: "white",
    backgroundColor: "#ac5353"
    padding: "10px"
  };
  return (
    <div>
      <h1 style={{color: "orange"}}>Welcome to rect js application</h1>
      <h3 style={objectStyle}> Styling using JS Object</h3>
    </div>
  );
}
export default App;

CSS Stylesheet

You can write your CSS styling in a separate file, just save the file with the .css file extension, and import it in your application.

With an external stylesheet file, you can change the look of an entire website by changing just one file.

Add some style in app.css like below and use it in App.js component using className attribute and see the output.

Styling React js application

Styling React js application

App.css

.headerStyle{
  background-color: #282c34;
  color: white;
  padding: 40px;
  font-family: Sans-Serif;
  text-align: center;
}

App.js

function App() {
  const objectStyle = {
    color: "white",
    backgroundColor: "#ac5353",
    padding: "10px"
  };
  return (
    <div>
      <h1 style={{color: "orange"}}>Welcome to rect js application</h1>
      <h3 style={objectStyle}> Styling using JS Object</h3>
      <h4 className="headerStyle">Styling using CSS</h4>
    </div>
  );
}
export default App;

Summary

In this article, we have covered how to perform different types of styling in react js element. Just try it in your application and have fun with styling.