React CSS

 

React CSS

*     CSS – cascading style sheets

*     In React we use CSS to style the React APP (or) component.

*     3 ways to style React components

Ø Inline Styling

Ø CSS stylesheet

Ø CSS Module

Possible way of Adding CSS to React Components

Inline Styling:

To style an element with the inline style attribute, the value must be a Javascript object.The Styling must written inside two sets of curly braces{{}}

 

   If the properties have two names, like background-color, it must be written in Camel case syntax.

CSS Stylesheets

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.

CSS Modules:

v      CSS Modules are convenient for components that are placed in separate files.

v      The CSS inside a Module is available only for the component that imported it.

v      It means any styling you add can never be applied to other components without your permission ,and you do not have to worry about name conflicts.

v      You can create CSS Module with the module.css extension like a myStylesheet.module.css name.

Inline style CSS & External style CSS

Changes in index.js

import React from 'react';

import ReactDOM from 'react-dom/client';

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

 

const root = ReactDOM.createRoot(

  document.getElementById('root')

);

class Reactstyle extends React.Component{

  render(){

    return(

      <div>

      <h1 style={{color:"red",textAlign:"center"}}>Hello World</h1>

      <h2 style={mystyle}>Welcome</h2>

      <h3 className="App">Thank You</h3>   //External style CSS

      </div>

    )

    }

  }

 

 

var mystyle={color:'green',textAlign:'center'}

const element =<div ><Reactstyle/></div>;

 root.render(element);

 

 

Changes in App.css for App className in h3 tag

.App {

  text-align: center;

  color: slateblue;

  text-shadow: #282c34;

  background-color: tomato;

}

 

 

Output


CSS Module

Changes in index.js

import React from 'react';

import ReactDOM from 'react-dom/client';

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

import styles from './demo.module.css';

 

const root = ReactDOM.createRoot(

  document.getElementById('root')

);

class Reactstyle extends React.Component{

  render(){

    return(

      <div>

      <h1 style={{color:"red",textAlign:"center"}}>Hello World</h1>

      <h2 style={mystyle}>Welcome</h2>

      <h3 className={styles.heading}>Thank You</h3>

      </div>

    )

    }

  }

 

var mystyle={color:'green',textAlign:'center'}

const element =<div ><Reactstyle/></div>;

 root.render(element);

 

 

Create a new css file name demo.module.css file in src

In demo.module.css file

.heading{

color: rgb(217, 255, 0);

text-align: center;

background-color: violet;

}

 

 

Output

 


No comments:

Post a Comment