Page Content

Tutorials

What Are The Styling React Components With Example

Styling React Components

Styling React Components
Styling React Components

Developers must customise user interfaces with styling React components to create responsive and attractive apps. React.js component styles have different benefits and considerations. This lets developers select the solution that best suits the requirements of their project. In order to encourage reusability across projects, these techniques seek to maintain component-specific styles logically grouped with the component.

Overview of Styling Approaches in React

Three basic styling techniques are frequently used in React applications:

Plain Cascading Style Sheets (CSS): Standard CSS is written in external files and imported into styling React components using plain cascading style sheets (CSS).

Inline Styles with JavaScript Objects: JavaScript objects can be used to declare styles directly in the JavaScript code of your components. This technique is known as “inline styles.”

CSS Modules: The more structured CSS Modules solution uses standard CSS but locally scopes class names to avoid conflicts.

The way React applies styles is also impacted by JSX (JavaScript XML), a syntax extension that enables programmers construct HTML-like markup in JavaScript code. JSX corresponds to React calls.createElement and supports style attributes, among other uses.

Plain CSS (CSS Stylesheets)

Since using plain CSS stylesheets doesn’t require any further settings beyond what Create React App offers, it’s frequently regarded as the simplest method for styling React components. Using this technique, you create distinct.css files and import them straight into your JavaScript or React component files.

How it Works:

  • You provide your styles like in an HTML project and create a.css file (App.css, ExpenseEntryItem.css, etc.).
  • In your React component’s JavaScript file, import ‘./App.css’.
  • Webpack, a build tool for Create React App, adds imported CSS to the <style> tag at the beginning of the HTML file, which is rendered in the browser’s <head> element. The styles are gathered and packed during construction.

Applying Styles with className: One important distinction between utilising CSS in React’s JSX and conventional HTML is that the className property must be used. This is due to the fact that class is a JavaScript reserved keyword. For instance, <div className=”container”> would be written in place of <div class=”container”>. htmlFor is the camelCase equivalent of other HTML attributes like for.

Advantages:

Ease of Use: Its compatibility with conventional web development techniques makes it easy to use, particularly for beginners or modest projects.

Browser Efficiency: The ability of browsers to process and apply CSS stylesheets efficiently is greatly enhanced. The most frequent HTML styling react components method is separate CSS. Browsers apply styles rapidly and consistently, making this procedure fast. There are more HTML styling options. Standard HTML lets you specify inline styles directly on an element using the style property with a string of styles.

Disadvantages and Conflict Resolution:

The global scope of styles in larger React projects presents a significant challenge for basic CSS, as it might result in class name conflicts. When two distinct styling React components share a class name (for example, wrapper), their styles may inadvertently influence one another.

In order to lessen these disputes:

Prefixing Class Names: One popular practice is to prefix class names with the component’s name (for example, alert-wrapper for an alert component). Even better, you may use template literals to combine dynamic values from props with static prefixes (className={`alert-wrapper ${type}`}, for illustration).

Child Combinators (>): This CSS child combinator (>) can be used in your selectors (e.g.,.alert-wrapper > h2) to make sure styles only apply to a component’s immediate children and not deeply nested elements. By doing this, styles are kept from “leaking” to unwanted child styling React components.

These solutions are available, but in large or heavily layered applications, they can become complicated, making it challenging to create rules that apply exactly without causing unexpected side effects.

Code Example:

import React from "react";
function Alert({ type }) {
  return (
    <div className={`alert-wrapper ${type}`}>
      <h2>This is a {type} message!</h2>
      <p>Something went {type === "success" ? "right" : "wrong"}.</p>
    </div>
  );
}
// The key change is adding 'export default' here
export default function App() {
  return (
    <>
      <style>{`
        .app-container {
          font-family: Arial, sans-serif;
          text-align: center;
          padding: 20px;
        }
        .alert-wrapper {
          
          padding: 15px;
          margin: 10px auto;
          width: 300px;
         
          background-color: #f9f9f9;
        }
        .alert-wrapper > h2 {
          margin: 0;
          font-size: 1.5em;
        }
        .alert-wrapper.success {
         
          color: green;
        }
        .alert-wrapper.error {
          
          color: red;
        }
      `}</style>
      <div className="app-container">
        <h1>Plain CSS in React Example</h1>
        <Alert type="success" />
        <Alert type="error" />
      </div>
    </>
  );
}

Output:

Plain CSS in React Example

This is a success message!
Something went right.
This is a error message!
Something went wrong.

Inline Styles with JavaScript Objects

Using the style feature, which takes a JavaScript object, you may immediately embed styles into your JSX elements with React’s inline styling react components. Traditional HTML inline styles, on the other hand, call for a string of CSS properties.

How it Works:

  • JavaScript object keys are CSS property names and values are style values.
  • CSS property names are changed to camelCase from kebab-case.
  • If padding or margin values are not specified as a string (like “20%”), React often converts them to pixels (px).

The style object is appended to a JSX element’s style attribute using curly brackets (e.g., <div style={myStyleObject}>). You may also declare the object directly in the style property using double curly brackets (e.g., <div style={{color: ‘brown’}}>).

Advantages:

Dynamic Styling: Setting CSS properties using JavaScript logic, variables, and props is a major benefit of dynamic style. Because of this, it is effective at determining styles in real time or when styles rely on the state or props of the component.

No Class Name Conflicts: Class name conflicts between styling React components are eliminated because styles are applied directly to individual elements, making naming conventions simpler.

Predictability: Because styles are generated in real time, they can utilise any supported JavaScript syntax and are hence more predictable.

Disadvantages:

Performance Cost: By not utilising browser optimisations for handling CSS stylesheets, applying styles inline may result in a performance cost.

Limited Cascading: Applying styles that target particular element types broadly or cascade to child elements is more difficult with limited cascading (e.g., establishing a font family for all elements). Every element must have its style clearly stated or transmitted.

CSS Pseudo-Classes/Elements: Generally speaking, inline styles do not directly support CSS pseudo-classes (such as :hover, :active) or pseudo-elements (such as ::before, ::after) [external knowledge, although pertinent to “basic styling”].

Code Example:

import React from 'react';
function App() {
  const myStyle = {
    color: 'white',
    backgroundColor: 'teal',
    padding: 20,
    borderRadius: '10px',
    textAlign: 'center',
    fontFamily: 'Arial'
  };
  return (
    <div style={myStyle}>
      <h1>Inline Styling in React</h1>
      <p>This box is styled using a JavaScript object.</p>
    </div>
  );
}
export default App;

Output:

Inline Styling in React
This box is styled using a JavaScript object.

CSS Modules

The global scope issue with plain CSS is resolved by CSS Modules, which also let you use conventional CSS syntax. CSS modules create locally scoped CSS styles for React apps, making style definition and management safe and easy. By making each class name unique across all components, this strategy eliminates class name conflicts in larger projects caused by plain CSS.

How it Works:

When you create CSS files, you usually follow a specified naming pattern, such as styles.module.css. Webpack automatically creates locally scoped class names for these files when imported into styling React components. This prevents module class names from clashing with identical ones in another. Instead of passing className a string, you import the module (e.g., styles from ‘./MyComponent.module.css’). Use the class name of the imported styles object as a property (e.g., <div className={styles.wrapper}>).

Advantages:

No Class Name Conflicts: class names are automatically scoped locally, reducing global clashes. This lets developers use clear, descriptive class names without worrying about unwanted consequences.

Familiar CSS Syntax: Developers that are already familiar with CSS can write CSS using standard syntax. React’s “Familiar CSS Syntax” lets you styling React components with plain CSS, like in an HTML project. Developers can import stylesheets directly into styling React components to firmly relate component-specific styles to JavaScript and JSX.

Co-location: Co-location in React development groups code and assets relevant to a component into the same directory rather than by file type. This means that a component’s JavaScript, CSS, and pictures live in its designated folder rather than in top-level directories.

Disadvantages:

Build Tool Dependency: React development uses “Build Tool Dependency” to refer to the software tools and packages needed to turn code into a deployable, production-ready application. These technologies are essential because recent React apps use complex JavaScript capabilities and JSX, which browsers cannot read.

Learning Curve: The reference and modular import styles are new, although the CSS syntax is well-known.For novices, className may have a small learning curve [external knowledge].

Conclusion

To sum up, React offers developers a variety of stylistic tools that let them include styles straight into their component-based architecture. Because of its worldwide reach, plain CSS requires careful naming or combinator usage to prevent conflicts, even though it is straightforward for small applications. Despite their ability to remove naming conflicts and provide dynamic styling react components, inline styles may have limitations in cascading styles and performance issues.

CSS Modules handle styles in larger applications well due to their automated local scoping and standard CSS syntax. Project size, team preferences, and requirements influence decision-making. No solution is “best” in the end. Developers can refactor from simpler methods to keep styling React components manageable and well-styled as the project evolves.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index