React CSS

Inline Styling

To style an element with the inline style attribute, the value must be a JavaScript object

class Profile extends React.Component {
  render() {
    return (
      <div>
      <h1 style={{color: "red"}}>Hello World!</h1>
      </div>
    );
  }
}

In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects also use curly braces, the styling in the example above is written inside two sets of curly braces {{}}

camelCased Property Names

Since the inline CSS is written in a JavaScript object, properties with two names, like background-color, must be written with camel case syntax:

class Profile extends React.Component {
  render() {
    return (
      <div>
      <h1 style={{backgroundColor: "lightblue"}}>Hello World!</h1>
      </div>
    );
  }
}

Javascript Object

You can also create an object with styling information, and refer to it in the style attribute.

class Profile extends React.Component {
  render() {
    const mystyle = {
      color: "white",
      backgroundColor: "blue",
      padding: "10px",
      fontFamily: "Arial"
    };
    return (
      <div>
      <h1 style={mystyle}>Hello World!</h1>
      </div>
    );
  }
}

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.

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';

class Profile extends React.Component {
  render() {
    return (
      <div>
      <h1>Hello World!</h1>
      </div>
    );
   
}
}

ReactDOM.render(<Profile />, document.getElementById('root'));

CSS Module

Another way of adding styles to your application is to use CSS Modules. CSS Modules are convenient for components that are placed in separate files.

.myBlue {
  color: blue;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './mystyle.module.css'; 

class Profile extends React.Component {
  render() {
    return <h1 className={styles.myblue}>Hello World!</h1>;
  }
}

export default Profile;

 

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *