📜 ⬆️ ⬇️

React Training Course, Part 15: Workshop on Working with Component State

Today we offer you to perform two practical classes on working with the state of the components. In particular, by completing today's tasks, you can not only better understand the concept of properties, but also work on debugging React-applications in which there are errors.

image

Part 1: Course Overview, React, ReactDOM, and JSX Reasons
Part 2: Functional Components
Part 3: Component Files, Project Structure
Part 4: Parent and Child Components
Part 5: Getting Started on a TODO Application, Basics of Styling
Part 6: Some of the features of the course, JSX and JavaScript
Part 7: Inline Styles
Part 8: continued work on the TODO application, familiarity with the properties of components
Part 9: Component Properties
Part 10: Workshop on working with the properties of components and styling
Part 11: dynamic markup generation and the map array method
Part 12: workshop, the third stage of work on the TODO application
Part 13: Class Based Components
Part 14: Workshop on Class Based Components, Component State
Part 15: workshops on working with the state of components

Lesson 27. Workshop. Component Status, Debugging


Original

▍Job


Analyze the following App class code from the App.js file of the standard React application created by create-react-app . This code is incomplete, it has errors.

 import React from "react" class App extends Component() {   return (       <div>           <h1>{this.state.name}</h1>           <h3><font color="#3AC1EF">▍{this.state.age} years old</font></h3>       </div>   ) } export default App 

An App component based on a class does not have a constructor, its state is not initialized, but when forming what it returns, it means that it has a state with some data.

Your task is to bring this code into working condition.

If you encounter some unknown error message - do not rush to look into the solution. Try it yourself, for example, carefully read the code and look for information about the problem on the Internet, find out the cause of the error and fix it. Debugging code is a valuable skill that will definitely come in handy when working on real projects.

▍Decision


The body of a class is similar to the body of a functional component. It only has a return command, but in class-based components, this command is used in the render() method, not in the body of the class. Fix it.

 import React from "react" class App extends Component() {   render() {       return (           <div>               <h1>{this.state.name}</h1>               <h3><font color="#3AC1EF">▍{this.state.age} years old</font></h3>           </div>       )   } } export default App 

If we continue the analysis of the code, looking at the error messages displayed in the browser, it can be understood that although the class App extends Component construction looks quite normal, with what we refer to as the Component , there is still something wrong. The problem is that in the import command, import React from "react" , we import only React into the project, but not the Component . That is, we need to either edit this command, bringing it to import React, {Component} from "react" , then when creating a class we can use the already existing code, or rewrite the class declaration in this form: class App extends React.Component . We will focus on the first option. Now the component code looks like this:

 import React, {Component} from "react" class App extends Component() {   render() {       return (           <div>               <h1>{this.state.name}</h1>               <h3><font color="#3AC1EF">▍{this.state.age} years old</font></h3>           </div>       )   } } export default App 

True, this problem does not end there. The application does not work, the TypeError: Cannot set property 'props' of undefined error message appears in the browser TypeError: Cannot set property 'props' of undefined , we are informed that something is wrong with the first line of the class declaration.

The point here is that when declaring a component, which, as we already understood, is a component that is based on a class, after the name of the parent class there is a pair of parentheses. They are not needed here, this is not a functional component, so we will get rid of them. Now the application code is more or less efficient, the component based on the class no longer looks completely wrong, but the system continues to report errors to us. Now the error message looks like this: TypeError: Cannot read property 'name' of null . Obviously, it refers to an attempt to use data stored in a component state that has not yet been initialized. Therefore, now we will create a class constructor, not forgetting to call super() in it, and initialize the state of the component, adding to it the values ​​that the component is trying to work with.

Here is the finished working code for the App component:

 import React, {Component} from "react" class App extends Component {   constructor() {       super()       this.state = {           name: "Sally",           age: 13       }   }     render() {       return (           <div>               <h1>{this.state.name}</h1>               <h3><font color="#3AC1EF">▍{this.state.age} years old</font></h3>           </div>       )   } } export default App 

This is how the application page will look like in a browser.


Application page in the browser

Session 28. Workshop. The state of the components, working with data stored in the state


Original

In this practice session, you will have another chance to work with the state of the components.

▍Job


Below is the code of the functional component. Taking it as a basis, do the following:

  1. Convert it so that the component has a state.
  2. In the component state, the isLoggedIn property should be present, storing the boolean value true if the user is logged in, and false if not (in our case there are no “logon" mechanisms here, the corresponding value must be set manually when the state is initialized).
  3. Try to make sure that if the user is logged in, the component would You are currently logged in text You are currently logged in , and if not, then the text You are currently logged out . This task is optional, if you have difficulties in carrying it out, you can, for example, search for ideas on the Internet.

Here is the code for the App.js file:

 import React from "react" function App() {   return (       <div>           <h1>You are currently logged (in/out)</h1>       </div>   ) } export default App 

▍Decision


We have a functional component at our disposal. In order to equip it with a state, it must be converted into a component based on the class and initialized with its state. Here is the code for the converted component:

 import React from "react" class App extends React.Component {   constructor() {       super()       this.state = {           isLoggedIn: true       }   }     render() {       return (           <div>               <h1>You are currently logged (in/out)</h1>           </div>       )   } } export default App 

Check the performance of the application.


Application in browser

In fact, if you yourself have come to this point, it means that you have learned the course material on the components based on the classes and the state of the components. Now we will be engaged in the optional task.

In essence, we will discuss what needs to be done to complete this task in a lesson that is devoted to conditional rendering, so here we are a little ahead. So, we are going to declare and initialize a variable that will contain an in or out string, depending on what is stored in the isLoggedIn state isLoggedIn . We will work with this variable in the render() method, first analyzing the data and writing down the desired value into it, and then using it in the JSX code returned by the component. This is what we ended up with:

 import React from "react" class App extends React.Component {   constructor() {       super()       this.state = {           isLoggedIn: true       }   }     render() {       let wordDisplay       if (this.state.isLoggedIn === true) {           wordDisplay = "in"       } else {           wordDisplay = "out"       }       return (           <div>               <h1>You are currently logged {wordDisplay}</h1>           </div>       )   } } export default App 

Note that the wordDisplay variable is a regular local variable declared in the render() method, so to access it within this method, you just need to specify its name.

Here is what the application page will now look like:


Application page in the browser

The isLoggedIn state isLoggedIn set to true , so the page displays the text You are currently logged in . To display the text You are currently logged out you need to change, in the component code, the isLoggedIn value to false .

It should be noted that this problem can be solved in other ways. But the code that we got is clear and workable, so we’ll stop on it, although, for example, given that isLoggedIn is a logical variable, the if (this.state.isLoggedIn === true) condition if (this.state.isLoggedIn === true) can be rewritten as if (this.state.isLoggedIn) .

Results


Today you practiced working with the state of components, in particular, you fixed errors in your code, reworked the functional component into a component based on classes, did conditional rendering. The next time you are waiting for another practical work and a new topic.

Dear readers! Did you manage to find and correct all the mistakes yourself, performing the first of the practical works presented here?

Source: https://habr.com/ru/post/438988/