What are the Different ways to Style React Component

    Apr 04, 2023       by Suraj Roy

As Developer, We should be aware of all the ways to do a task, So we can perform the job more effeciently. If we talk about styling the componet there are also different ways for the same, including:

1. Inline Styles:

Inline styles can be added directly to a component using the style attribute in JSX. Inline styles are defined as an object with CSS property-value pairs.

 

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

 

2. CSS Modules

CSS Modules is a feature of CSS that allows developers to write modular and reusable CSS classes. With CSS Modules, CSS classes are scoped to a particular component, preventing naming conflicts.

 

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

 

3. CSS-in-JS libraries

There are several CSS-in-JS libraries that allow developers to write CSS styles in JavaScript. These libraries include styled-components, emotion, and glamorous.

Example (using styled-components):

 

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

 

4. CSS frameworks

CSS frameworks like Bootstrap or Material UI provide pre-built styles and components that can be used in React applications.

Example (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 World!</Button>
  );
};
 

 

5. Normal CSS

In this way, We basically follow the general approach of external CSS where we define the styling in an external CSS file and import it wherever needed.

 

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

 

External css file(index.css):

.button {

  background-color: 'blue',

  color: 'white',

  padding: '10px'

}

 

There are a few more methods to Style the Components but the above listed are the ways that are majorly used. 

Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You


WHAT'S NEW

Find other similar Articles here: