Loading lessons...
JSX Attributes & Inline Styling
JSX Attributes & Inline Styling
Attributes in JSX configure element behavior and styling. They accept either string literals or dynamic JavaScript expressions.
String Attributes vs Dynamic Attributes
When passing string values, use double quotes. When passing numbers, booleans, objects, or variables, wrap them in curly braces { }.
function Avatar() {
const imageUrl = "https://example.com/user.jpg";
const imageSize = 100;
const isDisabled = true;
return (
<img
src={imageUrl}
width={imageSize}
height={imageSize}
alt="User Profile"
disabled={isDisabled}
/>
);
}
Inline Styles in JSX
In standard HTML, styles are passed as string attributes (style="color: blue;"). In JSX, the style attribute takes a JavaScript object.
function AlertBox() {
const alertStyles = {
color: '#721c24',
backgroundColor: '#f8d7da',
padding: '12px 20px',
borderRadius: '4px',
border: '1px solid #f5c6cb'
};
return <div style={alertStyles}>Warning: System maintenance tonight!</div>;
}
The Double-Curly Brace Syntax style={{ ... }}
If you write an inline style object directly inside JSX, it requires double curly braces: the outer set for JSX evaluation, and the inner set for the JS object literal.
// Outer { } evaluates JS, inner { } defines style object
<h1 style={{ color: 'navy', fontSize: '24px' }}>
Styled Header
</h1>
Summary & TL;DR
- String attribute values use quotes (
alt="avatar"); dynamic attribute values use curly braces (width={100}). - The
styleattribute in React requires a JavaScript object with camelCase property names (e.g.backgroundColor,fontSize). - Inline objects use double curly braces
style={{ key: 'value' }}.