Styling React Components: Inline Styles vs CSS Modules

2024-07-27

Using Inline Styles (Not Recommended):

This method involves defining styles directly within your JSX code using JavaScript objects. However, inline styles lack the ability to use pseudo-classes like :hover which are specifically designed for hover effects.

As a workaround, you could manage a state variable to track the hover state. Then, conditionally apply different styles to the element based on the state value. This approach can become cumbersome and less readable, especially for complex components.

Recommended Approaches:




const Button = () => {
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseEnter = () => setIsHovered(true);
  const handleMouseLeave = () => setIsHovered(false);

  const styles = {
    backgroundColor: isHovered ? 'lightblue' : 'white',
  };

  return (
    <button style={styles} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
      Hover me
    </button>
  );
};

This example uses a state variable isHovered to track the hover state. It conditionally applies a background color based on the state value. Event handlers are used to update the state on mouse enter and leave events.

CSS Modules (Recommended):

// Button.module.css
.button {
  background-color: white;
  cursor: pointer;
}

.button:hover {
  background-color: lightblue;
}

const Button = () => {
  const classes = useStyles(); // Import styles from CSS Modules

  return (
    <button className={classes.button}>Hover me</button>
  );
};

export default Button;

This example uses CSS Modules. A separate CSS file (Button.module.css) defines styles for the button, including the hover state using :hover. The component imports the styles and applies the class name (classes.button) to the button element in JSX.




  1. Regular CSS:

This is the most basic approach. You can define your styles in a separate .css file and apply the class names to your JSX elements. While this works, it can lead to naming conflicts if you're not careful. It also doesn't offer the same level of component-specific styling as CSS Modules or Styled Components.

// styles.css
.button {
  background-color: white;
  cursor: pointer;
}

.button:hover {
  background-color: lightblue;
}

const Button = () => {
  return (
    <button className="button">Hover me</button>
  );
};
  1. CSS-in-JS Libraries (e.g., Emotion, Styled-JSX):

These libraries allow you to write CSS directly within your React components using JavaScript objects or template literals. Similar to Styled Components, they offer automatic scoping and easier styling of components with features like hover effects using pseudo-classes. Here's an example using Emotion:

import styled from '@emotion/styled';

const Button = styled.button`
  background-color: white;
  cursor: pointer;

  &:hover {
    background-color: lightblue;
  }
`;

const MyComponent = () => {
  return (
    <div>
      <Button>Hover me</Button>
    </div>
  );
};
  1. Utility-First CSS Frameworks (e.g., Tailwind CSS):

These frameworks provide pre-built CSS classes for various styles, including hover effects. You can directly apply these classes to your JSX elements to achieve the desired look. While convenient, these frameworks can add extra weight to your project if you're not using a lot of their features.

const Button = () => {
  return (
    <button className="bg-white hover:bg-blue-200 px-4 py-2 rounded">Hover me</button>
  );
};

reactjs



Understanding React JSX: Selecting "selected" on a Selected <select> Option

Understanding the <select> Element:The <select> element in HTML represents a dropdown list.It contains one or more <option> elements...


Understanding Virtual DOM: The Secret Behind React's Performance

Imagine the Virtual DOM (VDOM) as a lightweight, in-memory copy of your React application's actual DOM (Document Object Model). It's a tree-like structure that mirrors the elements on your web page...


Keeping Your React Components Clean: Conditional Rendering and DRY Principles

ReactJS provides several ways to conditionally render elements based on certain conditions. Here are the common approaches:...


Understanding Parent-Child Communication in React: The Power of Props

Here's a breakdown of the process:Parent Component:Define the data you want to pass as props within the parent component...


Example Codes:

In JavaScript, for is a reserved keyword used for loop constructs.When you directly use for as an attribute in JSX (React's syntax for creating HTML-like elements), it conflicts with this keyword's meaning...



reactjs

Beyond window.resize: Effective Methods for Responsive Layouts in React

When a user resizes the browser window, you want your React application to adapt its layout and elements accordingly. This ensures a visually appealing and functional experience across different screen sizes


Accessing Custom Attributes from Event Handlers in React

React allows you to define custom attributes on HTML elements using the data-* prefix. These attributes are not part of the standard HTML specification and are used to store application-specific data


Unveiling the Secrets of React's Performance: How Virtual DOM Beats Dirty Checking

Directly updating the DOM (Document Object Model) in JavaScript can be slow. The DOM represents the structure of your web page


Communicating Between React Components: Essential Techniques

React applications are built from independent, reusable components. To create a cohesive user experience, these components often need to exchange data or trigger actions in each other


Unlocking Dynamic Content in React: Including Props Within JSX Quotes

In React, components can receive data from parent components through properties called props.These props allow you to customize the behavior and appearance of child components