JSX, an extension of JavaScript, eases the process of writing and adding HTML in React. You might already be aware that CSS styles in JSX slightly differ from HTML. Specifically, the way you use inline styles in JSX is unlike how you do it conventionally within HTML.
Considering the quiz question, the correct way to write an inline style which specifies font-size:12px
and color:red
in JSX would be style={{fontSize:'12px',color:'red'}}
.
In JSX, the style
attribute accepts a JavaScript object instead of a CSS string. Hence, to include CSS properties, you must use an object with key-value pairs. The keys are written in camelCase, i.e., without hyphens (-
), and represent the CSS properties. On the other hand, the values (also written within single or double quotes) represent the actual style you want to apply.
Looking at our inline style example, fontSize:'12px'
and color:'red'
are CSS properties specified in JSX. fontSize
corresponds to the CSS property font-size
, and '12px'
is the value. Similarly, color
stands for the CSS property with the same name, and 'red'
is the specified color.
{{}}
While writing inline styles in JSX, it's crucial to wrap the style object within double curly braces, like so style={{fontSize:'12px',color:'red'}}
. The outer pair of braces is for embedding a JavaScript expression, while the inner pair creates a JavaScript object literal.
Consider you are designing a warning message for a function component in React. You want the text to be small (12px) and red, so it catches the user's attention. You can do so with the correct inline style:
function WarningMessage() {
return (
<p style={{fontSize:'12px',color:'red'}}>
Attention: Please fill out all required fields.
</p>
);
}
margin
, padding
, fontSize
) can also be written without the quotes and unit, e.g., fontSize:12
is also valid in JSX, assuming the size unit as pixels.By understanding the unique syntax of inline styles in JSX, you can efficiently style your React elements and create dynamic, visually pleasing web applications.