React allows you to change an element’s appearance dynamically using JavaScript values, expressions, props, and state.
In a traditional website, CSS styles are often fixed:
<p className="title">Welcome to React</p>
The .title class defines how the text looks.
In React, you can make styling respond to application data:
const isActive = true;
<p
style={{
color: isActive ? "green" : "gray"
}}
>
Account Status
</p>
Now the text color depends on the value of isActive.
Dynamic styles are useful when an application’s appearance needs to change based on:
- Component state
- User actions
- Props
- API data
- Form validation
- Loading states
- Themes
- User preferences
- Product availability
- Scores and progress
- Screen or application conditions
React provides several ways to create dynamic styling, including inline style objects, conditional class names, CSS variables, and external styling systems.
What Are Dynamic Styles?
Dynamic styles are styles whose values can change based on JavaScript data.
For example:
const color = "blue";
return (
<p style={{ color }}>
Hello React
</p>
);
The value of color determines the text color.
The important pattern is:
style={{
property: value
}}
The value can come from a variable:
color
a calculation:
isActive ? "green" : "gray"
a prop:
theme.primaryColor
or state:
isDarkMode ? "#fff" : "#000"
Static Styles vs Dynamic Styles
A static style does not depend