Styling in React

Inline Styling and CSS Modules

Inline Styling

Inline styles in React are defined using JavaScript objects. Each CSS property is written in camelCase, and values are passed as strings or variables.


function InlineStyledBox() {
  const style = {
    backgroundColor: 'lightblue',
    padding: '20px',
    borderRadius: '8px'
  };

  return <div style={style}>This box is styled inline.</div>;
}
  

Inline styles are useful for dynamic or quick styling, but they lack support for pseudo-classes (like :hover) and media queries.

CSS Modules

CSS Modules allow you to write CSS in a separate file and scope it locally to the component, preventing class name collisions.

Create a CSS file with the .module.css extension, for example:

/* styles.module.css */
.container {
  background-color: lavender;
  padding: 16px;
  border-radius: 8px;
}
  

Then import and use it in your component:


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

function ModuleStyledBox() {
  return <div className={styles.container}>Styled with CSS Modules</div>;
}
  

Styled Components and CSS-in-JS

Styled Components

Styled Components is a popular library for writing actual CSS in your JavaScript using tagged template literals. It enables dynamic styling and automatic class scoping.

Install the library:

npm install styled-components

Example usage:


import styled from 'styled-components';

const Box = styled.div`
  background-color: peachpuff;
  padding: 20px;
  border-radius: 10px;
`;

function StyledComponentBox() {
  return <Box>Styled using Styled Components</Box>;
}
  

Other CSS-in-JS Solutions

Besides Styled Components, there are other CSS-in-JS libraries such as Emotion, JSS, and Stitches. These libraries offer similar capabilities, often with different APIs and performance trade-offs.

Best Practices for Scalable Styling

  • Use CSS Modules or CSS-in-JS for component-scoped styling.
  • Organize styles close to components (co-located CSS or styled files).
  • Use BEM or naming conventions to avoid conflicts when using global styles.
  • Prefer logical styles (e.g., padding-block vs padding-top) for internationalization and accessibility.
  • Avoid overusing inline styles except for dynamic styling needs.
  • Use variables or design tokens for consistent theming.
  • Leverage tools like Tailwind CSS if you prefer utility-first CSS approaches.

Conclusion

React provides flexibility in styling your components, from inline styles and CSS Modules to powerful CSS-in-JS solutions like Styled Components. Choosing the right approach depends on your project size, team preferences, and performance needs. In the next post, we’ll explore React Hooks — one of the most powerful features of modern React development.

Post a Comment

0 Comments