React Tutorial, Part 7: Inline Styles

Original author: Bob Ziroll
  • Transfer
  • Tutorial
Today, in the next part of the React course, we’ll talk about inline styles. → Part 1: course overview, reasons for the popularity of React, ReactDOM and JSXPart 2: functional componentsPart 3: component files, project structurePart 4: parent and child componentsPart 5: starting work on a TODO application, basics of stylingPart 6: about some features of the course, JSX and JavaScriptPart 7: inline stylesPart 8: continued work on a TODO application, familiarity with the properties of componentsPart 9: properties of components

image










Part 10: workshop on working with component properties and styling
Part 11: dynamic markup generation and array method map
Part 12: workshop, third stage of working on a TODO application
Part 13: class-based components
Part 14: workshop on class-based components, component state
Part 15: workshops on working with component state
Part 16: fourth stage of working on a TODO application, event handling
Part 17: fifth stage of working on a TODO application, modifying component state
Part 18 : over that phase of work on TODO-application
Part 19: component life cycle methods
Part 20: first lesson on conditional rendering
Part 21: second lesson and practice on conditional rendering
Part 22: seventh stage of working on a TODO application, loading data from external sources
Part 23: first lesson on working with forms
Part 24: second lesson on working with forms
Part 25: a workshop on working with forms
Part 26: application architecture, Container / Component pattern
Part 27: course project

Lesson 15: Inline Styles


Original

At the end of the last lesson we created a component that analyzes the time of day and displays the corresponding greeting. Here is the complete file code index.jsthat implements this functionality:

import React from"react"import ReactDOM from"react-dom"functionApp() {
  const date = newDate()
  const hours = date.getHours()
  let timeOfDay
  
  if (hours < 12) {
    timeOfDay = "morning"
  } elseif (hours >= 12 && hours < 17) {
    timeOfDay = "afternoon"
  } else {
    timeOfDay = "night"
  }
  
  return (
    <h1>Good {timeOfDay}!</h1>
  )
}
ReactDOM.render(<App />, document.getElementById("root"))

Now we need to stylize what this code displays on the page. In this case, we are going to use an approach here that differs from the styling of elements discussed earlier using CSS classes. Namely, we are talking about the use of HTML-attribute style. Let's see what happens if we use this design:

<h1 style="color: #FF8C00">Good {timeOfDay}!</h1>

Actually - nothing good. The text on the page will not get, instead, an error message will be displayed. Its essence boils down to the fact that here, when setting styles, it is expected not a string value, but an object containing pairs of the form ключ: значение, where the keys are the names of CSS properties, and the values ​​are their values.

When trying to use HTML attributes in JSX code, we should not forget that what we work with, although it looks like ordinary HTML code, is not. As a result, how this or that construction will look like here may differ from what is accepted in HTML. In this case, we need a regular JavaScript object containing a description of the styles. Armed with this idea, we will rewrite the above code snippet like this:

<h1 style={color: "#FF8C00"}>Good {timeOfDay}!</h1>

So, unfortunately, our code won't work either. As a result of its execution, an error message will again appear, but not the same as last time. It now reports that where the system can expect a brace, it finds something else. In order to solve this problem, you need to remember what we talked about in the previous lesson. Namely, the fact that the JavaScript code embedded in JSX must be enclosed in braces. Those braces that are already in our code are used to describe the object literal, and not to highlight the JS code. Fix this:

<h1 style={{color: "#FF8C00"}}>Good {timeOfDay}!</h1>

Now the component forms on the page exactly what you need.


Stylized text displayed on the page by a component.

What if we decide to continue styling this text? To do this, we need to remember that we describe the styles in the JS object, which means that we need to add additional view pairs to this objectключ: значение. For example, let's try to style the text background in this way using the CSS propertybackground-colorand add the code like this:

<h1 style={{color: "#FF8C00", background-color: "#FF2D00"}}>Good {timeOfDay}!</h1>

Such a construction will result in an error message. The point here is that we describe styles using a normal JS object, while in JavaScript variables and property names for objects ( identifiers ) cannot contain the “-” symbol, a dash. In fact, this restriction can be circumvented, for example, by enclosing the name of an object property in quotes, but in our case this is irrelevant. We are in such situations, when the names of CSS properties contain a dash, we remove this symbol and make the first letter of the word that follows it capitalized. It is easy to see that with this approach, CSS property names will be written in camel style - just as in JavaScript, it is customary to write variable names consisting of several words. Rewrite the code:

<h1 style={{color: "#FF8C00", backgroundColor: "#FF2D00"}}>Good {timeOfDay}!</h1>

Let's look at the results of his work.


Stylized text displayed on the page by a component.

In the process of styling text, the code of an object with styles becomes longer. Working with him is uncomfortable. If you try to break this code into several lines, nothing good will happen either. Therefore, we will render a description of an object with styles from JSX code, creating a constant with a namestyles, writing an object into it and using its name in JSX. As a result, we have the following:

const styles = {
    color: "#FF8C00", 
    backgroundColor: "#FF2D00"
  }
  
  return (
    <h1style={styles}>Good {timeOfDay}!</h1>
  )

This code works exactly the same as the one described above, but this approach is very convenient when it becomes necessary to add new styles to the object. This does not lead to the proliferation of code returned by the component.

As you can see, now the values ​​of CSS properties are set in the object stylesas strings. When working with this object, it is worth considering some features that, in particular, relate to properties, the values ​​of which are specified in the form of numbers. For example, this property fontSize(looking like font-sizein CSS). So, this property can be set as a regular number, not a string enclosed in quotes. For example, the following construction is quite acceptable:

const styles = {
    color: "#FF8C00", 
    backgroundColor: "#FF2D00",
    fontSize: 24
}

Here the number 24will be interpreted as a font size specified in pixels. If the unit of measurement needs to be specified explicitly, we will again need to use the string values ​​of the properties. For example, the following code snippet is similar, in terms of its effect on the font size, to the previous one, but the unit of measurement for size is here explicitly indicated:

const styles = {
    color: "#FF8C00", 
    backgroundColor: "#FF2D00",
    fontSize: "24px"
}

Here we have specified the size in pixels, but if necessary, other units of measurement can be used in similar constructions.

Speaking of built-in styles, one can not fail to mention the limitations of this approach. So, if you need to add browser prefixes to styles , this can be a bit more difficult than adding other styles. But something like pseudo clashes , such as :hover, is not supported. If you need it at this stage of React mastering, it will be best to take advantage of styling elements using CSS classes. And in the future, you will probably find it most convenient to use specialized libraries like styled-components for such purposes.. But now we restrict ourselves to inline styles and styling elements using CSS classes.

Perhaps after learning about this restriction of inline styles, you will wonder why you should use them if the CSS classes allow you to achieve the same effect and have more extensive capabilities. One of the reasons for using embedded styles in React is that such styles can be formed dynamically. In this case, what will be one or another style is determined by means of JavaScript code. Let's rewrite our example so that the text color would change depending on the time of day at which the message is displayed.

Here is the complete component code that uses dynamic styling.

functionApp() {
  const date = newDate()
  const hours = date.getHours()
  let timeOfDay
  const styles = {
    fontSize: 30
  }
  
  if (hours < 12) {
    timeOfDay = "morning"
    styles.color = "#04756F"
  } elseif (hours >= 12 && hours < 17) {
    timeOfDay = "afternoon"
    styles.color = "#2E0927"
  } else {
    timeOfDay = "night"
    styles.color = "#D90000"
  }
  
  return (
    <h1style={styles}>Good {timeOfDay}!</h1>
  )
}

Notice that the constant declaration is stylesnow in front of the block if. In the object that defines the style, only the font size of the label is set to 30pixels. Then a property is added to the object color, the value of which depends on the time of day. Recall that we are talking about a completely normal JavaScript object, and such objects support adding and changing properties after they are created. After the style is formed, it is applied when the text is displayed. In order to quickly test all branches of the conditional operator, you can, when initializing a constant date, pass the Datedesired date and time to the object constructor . For example, it might look like this:

const date = newDate(2018, 6, 31, 15)

As a matter of fact, the meaning of all this lies in the fact that dynamic data can affect how the elements formed by the components look. This opens up great opportunities for the developer.

Results


Today we talked about the built-in styles, their capabilities and limitations. In the next lesson, we will continue to work on the TODO application, as well as begin our acquaintance with the properties of the components, with the most important concept of React. Therefore, it is recommended that everyone involved in this course should continue to repeat everything and experiment with everything that we have taken out at this point before continuing our studies.

Dear readers! If you are well versed in React development, please tell us which libraries you use to style components.


Also popular now: