Inline Styles
Although I wouldn't recommend using elaborate styling inline, there might be a reason to do so. For example if you need to apply styles depending on a certain condition. For example, we need to change to color of the text when it is 11 o'clock:
const App = () => {
const hour = new Date().getHours()
const color = hour === 14 ? "#F0F" : "#000"
const style = { color: color }
return (
<div className="app-component">
<h1 style={ style }>{ hour }</h1>
<h2 style={{ backgroundColor: color, padding: 20 }}>
BackgroundColor changed!
</h2>
</div>
)
}
export default App
-
The inline styling
style={ ... }expects an object containing a style object, so pay close attention to the double braces. -
Also note that when using inline styles, all numeric units are in pixels, WITHOUT the
pxindication, and that all other variants must be included as text between quotes. So a 100% width with a centered text would become:width: "100%", textAlign: "center". -
Since the style attribute is an object, the various css elements are separated by a comma (instead of a semicolon).
-
Also take note of the notation. Since it is CSS inside JavaScript, you MUST use the JavaScript CSS Syntax (so
backgroundColorinstead ofbackground-color)