Inline styles in React
Inline styles
15
In React, inline styles are a way to apply styles directly to a component, rather than adding a CSS class to it. This can be useful when you want to style a component in a specific way that doesn't easily fit into an existing CSS class.
Inline styles in React use JavaScript objects instead of CSS syntax. To apply inline styles to a component, you pass a JavaScript object with style properties as the style
prop on the component.
For example:
<div style={{ color: 'red', fontSize: '24px' }}>Hello, world!</div>
In this example, the div
component is given an inline style with the color
and fontSize
properties set to 'red'
and '24px'
, respectively. Note that the curly braces inside the style
prop represent an expression in JSX, which evaluates to a JavaScript object containing the style properties.
One benefit of inline styles in React is that you can use JavaScript logic to dynamically generate styles based on component props or state.
For example:
function Button(props) { const styles = { backgroundColor: props.color, padding: '10px', borderRadius: '5px', color: 'white' }; return ( <button style={styles}>{props.label}</button> ); }
In this example, the Button
component generates an inline style object based on the color
prop it receives, and applies it to a button
element. This allows the button color to be customized from the parent component.
March 25, 2023