Inline Styles in React: A Practical Guide with Examples
Learn how to use inline styles effectively in your React components. This guide explains the syntax, best practices, and when inline styles are appropriate, comparing them to using `className` and external CSS files. Master both simple and more complex inline styling techniques in React.
Inline Styles in React: A Practical Guide
Introduction to Inline Styles in React
While inline styles (using the `style` attribute) are common in basic HTML, they are generally less preferred in React for larger projects. However, they can be useful for simple, dynamic styling within a component. This guide demonstrates inline styling using a user profile card example.
Styling Components in React: The Usual Way
Typically, React components are styled using the `className` attribute, referencing styles defined in a separate CSS file:
Traditional Styling
import React from "react";
import './style.css';
const MyComponent = () => (
<p className="paragraph-text">Class Name Styled Text</p>
);
Associated CSS (style.css)
.paragraph-text {
font-weight: bold;
color: beige;
}
Inline Styles in React
In React, inline styles are applied using the `style` attribute, which accepts a JavaScript object. Property names use camelCase (e.g., `backgroundColor` instead of `background-color`).
Inline Style Example
const MyComponent = () => (
<p style={{ color: 'blue', lineHeight: 10, padding: '1.5em' }}>Inline Styled Component</p>
);
Note that React automatically adds "px" to numeric values for some properties (like `padding`). If you need other units (e.g., "em"), specify them explicitly as strings (e.g., `padding: '1.5em'` ). Also, you are responsible for adding vendor prefixes (like `-webkit-`) if needed.
Improving Readability with Separate Style Objects
For more complex styling, it's better to define styles in a separate object to improve readability:
Improved Readability
const myComponentStyle = {
color: 'blue',
lineHeight: 10,
padding: '1.5em',
};
const MyComponent = () => (
<p style={myComponentStyle}>Inline Styled Component</p>
);
Building a User Profile Card Component
Let's create a user card component using inline styles:
User Profile Card Component
const cardStyles = {
// ... (style definitions as provided in the original text)
};
const UserCard = () => (
<div style={cardStyles.container}>
<div style={cardStyles.profilePicture}>D</div>
<div style={cardStyles.bio}>
<p style={cardStyles.userName}>Desmond Nyamador</p>
<p>I just learned an easy way to style React Components</p>
</div>
</div>
);
Best Practices
While inline styles can be convenient for simple cases, the official React documentation generally recommends using the `className` attribute and external stylesheets for larger projects to maintain better separation of concerns and improve maintainability.