YouTube Icon

Code Playground.

What are the Different ways to Style React Component

CFG

What are the Different ways to Style React Component

As Developer, We should be apprehensive of all the ways to do a task, So we can perform the job moreeffeciently.However, including 
If we talk about baptizing the componet there are also different ways for the same. 
1. Inline Styles 
Inline styles can be added directly to a element using the style trait in JSX. Inline styles are defined as an object with CSS property- value dyads. 

const MyComponent = () => {
  const style = {
    backgroundColor: 'blue',
    color: 'white',
    padding: '10px'
  };
 
  return (
    <div style={style}>Hello React!</div>
  );
};

2. CSS Modules 
CSS Modules is a point of CSS that allows inventors to write modular and applicable CSS classes. With CSS Modules, CSS classes are scoped to a particular element, precluding picking conflicts. 

import styles from './MyComponent.module.css';
const MyComponent = () => {
  return (
    <div className={styles.container}>Hello React!</div>
  );
};

3. CSS- in- JS libraries 
There are several CSS- in- JS libraries that allow inventors to write CSS styles in JavaScript. These libraries include nominated- factors, emotion, and glamorous. 

import styled from 'styled-components';
 
const Container = styled.div`
  background-color: blue;
  color: white;
  padding: 10px;
`;
 
const MyComponent = () => {
  return (
    <Container>Hello React!</Container>
  );
};

4. CSS fabrics 
CSS fabrics like Bootstrap or Material UI givepre-built styles and factors that can be used in React operations. 

illustration( using Material UI) 

import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
 
const useStyles = makeStyles({
  button: {
    backgroundColor: 'blue',
    color: 'white',
    padding: '10px'
  },
});
 
const MyComponent = () => {
  const classes = useStyles();
 
  return (
    <Button className={classes.button}>Hello React!</Button>
  );
};

5. Normal CSS 
In this way, We principally follow the general approach of external CSS where we define the styling in an external CSS train and import it wherever demanded. 

import "./index.css";
const MyComponent = () => {
 
  return (
    <Button className="button">Hello React!</Button>
  );
};

External css train(index.css) 

.button {
  background-color: 'blue',
  color: 'white',
  padding: '10px'
}

There are a many further styles to Style the Components but the below listed are the ways that are majorly used. 

Thank You! 
 




CFG