Inline StylesInline Styles

In React apps, we are familiar with using HTML-like code to create the markup. However, the default styling of our apps can be uninteresting and lackluster. This section will explore various widely-used techniques to transform our UI into a visually stunning experience.

Inline styles

One straightforward but somewhat limited approach to adding styles is using inline styles, similar to how we apply styles to HTML elements using the style attribute. In React, the only difference is that the value for this attribute is an object, not a string. The syntax is following:

The App component in the provided example includes the h1 element with inline styles defined using the style attribute. Here are some key points to remember about inline styles:

  • Property names with two or more words should follow the camel case (camelCase) notation. For instance, instead of using the CSS property font-weight, we use fontWeight.
  • When assigning values to CSS properties, we generally use strings, except for properties that expect plain numbers. This is why the fontWeight property uses a number as its value, while the fontSize property uses a string value.

Inline styles in the form of separate object

In the case of the style attribute, the value is a JavaScript object. To avoid cluttering the JSX code with CSS-related details, creating the style object separately as a variable is possible and assigning it to the style attribute. This approach helps keep the JSX code cleaner and more focused. How it works:

In this example, we introduce the appStyles object, representing the same styles used before but now as a separate object. This approach makes the App component cleaner, as the style attribute references the appStyles variable as its value. This separation of concerns improves the readability and maintainability of the component.

question-icon

How are inline styles applied in React components?

Select the correct answer

Everything was clear?

Section 2. Chapter 1