Chapter 2. Working with Properties and State
In the previous chapter, we set up our workflow. We worked out how to compile ReactJS and ES6 code through a build step, interpret it directly in our browser, and even run it using services such as JSBin. Now, we can begin creating components for our content management system.
In this chapter, we're going to start building our interface. We'll see interesting and effective ways to connect components. The important thing in this chapter is learning how to arrange components in complex hierarchies. We're going to nest several components and communicate between them and our data source, using a custom data backend.
Let's think about how we want to structure the components of our interface. Many content management systems feature lists of items—items that we store in and retrieve from a database. For example, let's imagine a system through which we can manage the pages of a website.
For such a system, we need an entry-point—something like PageAdmin
, which connects our persistence layer to our interface:
We can also represent the persistence layer in the form of a backend class:
Note
Later, we'll look at ways of persisting this data. For now, it's OK to just use static data in this class.
We could connect PageAdmin
to this...
So, how do we change from a PageView
class to a PageEditor
class? For that, we need to hook into browser events and fiddle with the state:
We're providing a way for child components to call methods in parent components by passing down methods child components can use. When a PageView
class wants to put the Page...
Component life cycle methods
There are a couple of tricks I want to show you before we wrap up. The first is a life cycle method we can use to tell when a component's properties will change. We can use this to change the appearance of a component, or refresh the internal state.
We can add this method to PageEditor
, for example:
In this chapter, you learned even more about ES6 classes and how they complement React components in structure and functionality. We also looked at some interesting uses of state and properties.
Above all, we saw how it's both possible and beneficial to avoid the internal component state. Properties are a powerful tool for component design. We know how to react to changing properties and how to reduce the work React needs to do to render our interfaces.
In the next chapter, we are going to discuss how to persist this data (to different kinds of local storage). We will see how to connect to these data stores through events.