HomeAbout Me

React Fundamental: Styling

By Daniel Nguyen
Published in React JS
May 07, 2025
2 min read
React Fundamental: Styling

🧠 Mastering Styling in React: From Basics to Custom Components

When building React applications, a key part of creating visually appealing and maintainable UIs is styling. This post walks you through the fundamentals of styling in React, how JSX relates to the DOM, and how to create a custom reusable <Box /> component that encapsulates consistent styling behavior.


🎨 Two Primary Ways to Style React Components

React supports two main methods for styling:

  1. Inline styles via the style prop
  2. CSS stylesheets via the className prop

Each approach has its strengths and tradeoffs, and understanding how JSX relates to HTML and the DOM is key to using them effectively.


πŸ” Understanding JSX: Properties vs Attributes

In HTML, you work with attributes like this:

<div class="my-class"></div>

But in React (JSX), you use DOM property names, not HTML attributes:

<div className="my-class" />

Why? Because JSX is syntactic sugar for JavaScript function calls (React.createElement). And React uses the DOM property equivalents under the hood. Here are a few key differences:

HTML AttributeJSX Prop
classclassName
forhtmlFor
tabindextabIndex
readonlyreadOnly

This distinction is important, especially when you’re debugging or dynamically setting properties.


πŸ’… Inline Styles in JSX

In HTML:

<div style="margin-top: 20px; background-color: blue;"></div>

In JSX, you pass an object, not a string:

<div style={{ marginTop: 20, backgroundColor: 'blue' }} />

A few key notes:

  • The outer {} tells JSX you’re injecting a JavaScript expression.
  • The inner {} defines the actual object.
  • Use camelCase instead of kebab-case.

βœ… Example:

const myStyles = { marginTop: 20, backgroundColor: 'blue' }
<div style={myStyles} />

⚠️ Limitations: No pseudo-classes (:hover, :focus) or media queries. For those, stick with regular CSS.


🧡 Styling with className

The most common way to style elements is still with CSS classes.

Step 1: Define your class in a CSS file:

/* index.css */
.my-class {
margin-top: 20px;
background-color: blue;
}

Step 2: Use it in your JSX:

<div className="my-class" />

Step 3: Make sure your CSS is loaded:

<link rel="stylesheet" href="index.css" />

In a real app, this might be handled automatically by your build tool (e.g., Vite, CRA, or Webpack).


🧱 Building a Custom <Box /> Component

Let’s reduce repetition and increase reusability by building a Box component that:

  • Always applies className="box" and style={{ fontStyle: 'italic' }}
  • Accepts additional className and style props from the user
  • Merges all of them properly

βœ… Desired Usage

<Box className="box--small" style={{ backgroundColor: 'lightblue' }}>
small lightblue box
</Box>

βœ… Expected Output (DOM)

<div
className="box box--small"
style={{ fontStyle: 'italic', backgroundColor: 'lightblue' }}
>
small lightblue box
</div>

βœ… Implementation

type BoxProps = React.ComponentProps<'div'>
function Box({ className = '', style = {}, ...props }: BoxProps) {
return (
<div
className={`box ${className}`}
style={{ fontStyle: 'italic', ...style }}
{...props}
/>
)
}

βœ… TypeScript Tip

To inherit all props from a native HTML element (like div), use:

React.ComponentProps<'div'>

This gives you full type safety and IntelliSense support in your custom component.


πŸ“ Add a size Prop for Better API Design

Now let’s improve the DX (Developer Experience) by replacing manual class names with a semantic size prop:

<Box size="small" style={{ backgroundColor: 'lightblue' }}>
small lightblue box
</Box>

βœ… Step-by-Step

  1. Define allowed sizes: 'small' | 'medium' | 'large'
  2. Generate the appropriate className (like box--small) internally
  3. Merge everything together

βœ… Updated Implementation

type BoxSize = 'small' | 'medium' | 'large'
type BoxProps = {
size?: BoxSize
} & React.ComponentProps<'div'>
function Box({ size, className = '', style = {}, ...props }: BoxProps) {
const sizeClassName = size ? `box--${size}` : ''
return (
<div
className={`box ${sizeClassName} ${className}`.trim()}
style={{ fontStyle: 'italic', ...style }}
{...props}
/>
)
}

βœ… Final Thoughts

By learning how JSX maps to the DOM and mastering both className and style usage in React, you’re now equipped to:

  • Write cleaner, more expressive UI code
  • Create reusable styled components
  • Improve API design with semantic props like size

This is a foundational skill every React developer should master. Keep exploring and experimenting β€” you’ll build beautiful, scalable UIs in no time!


πŸ“š Resources

  • React Docs – Styling and CSS
  • MDN – CSSStyleDeclaration
  • TypeScript Handbook – Intersection Types

Happy styling! 🎨✨


Tags

#ReactFundamental

Share

Previous Article
React Fundamental: TypeScript

Table Of Contents

1
🎨 Two Primary Ways to Style React Components
2
πŸ” Understanding JSX: Properties vs Attributes
3
πŸ’… Inline Styles in JSX
4
🧡 Styling with className
5
🧱 Building a Custom <Box /> Component
6
πŸ“ Add a size Prop for Better API Design
7
βœ… Final Thoughts

Related Posts

React Fundamental: Rendering Arrays
May 11, 2025
3 min
Β© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media