Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Inline Styles in Practice | Styling in React Apps
React Mastery
course content

Course Content

React Mastery

React Mastery

1. Introduction to React Fundamentals
2. Styling in React Apps
3. React Hooks and Context
4. React in the Real World

bookInline Styles in Practice

Let's create a versatile Notification component that displays text and dynamically changes the background-color property based on the behavior prop. We will proceed with the implementation step-by-step.

Step 1

We begin by creating the parent component, App, along with the child component, Notification, using the basic structure of React.

Step 2

To provide default styling for the Notification component, we create an object called notificationStyles and assign the following properties: padding with the value of "20px"; fontSize with the value of "24px"; color with the value of "aquamarine";

Let's assign the notificationStyles object as the value to the style attribute of the Notification component, which is applied to the returned p element.

Step 3

In the App component, we can utilize the Notification component by passing the behavior prop and the text prop. The behavior prop determines the appearance of the notification, while the text prop specifies the text to be displayed within the notification.

Step 4

We can implement the logic to colorize the background of each notification message based on the behavior prop in the following way:

  • If the value of behavior is "positive", the background color should be set to green;
  • If the value of behavior is "negative", the background color should be set to red;
  • If the value of behavior is "neutral", the background color should be set to blue.

We can create a function to handle the logic using the JavaScript switch statement. Here's an example of how it can be implemented:

This function takes the behavior prop as an argument and returns the corresponding background color based on the value using the switch statement. The behavior prop will return a transparent background color if it does not match the specified cases.

Let's incorporate this function into the style object of the component:

We utilize JavaScript conventions to ensure the proper structure of the style object. First, we spread the existing notificationStyles object. Then, we introduce an additional property, backgroundColor, whose value is derived from the string returned by the setBackgroundColor function.

Full app code:

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
some-alt