Reader small image

You're reading from  React Components

Product typeBook
Published inApr 2016
Publisher
ISBN-139781785889288
Edition1st Edition
Tools
Right arrow
Author (1)
Christopher Pitt
Christopher Pitt
author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt

Right arrow

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.

Nesting components


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:

import React from "react";

class PageAdmin extends React.Component {
    render() {
        return <ol>...page objects</ol>;
    }
}

export default PageAdmin;

We can also represent the persistence layer in the form of a backend class:

class Backend {
    getAll() {
        // ...returns an array of pages
    }

    update(id, property, value) {
        // ...updates a page
    }

    delete(id) {
        // ...deletes a page
    }
}

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...

Shared component actions


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:

class Page extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            "isEditing": false
        };
    }

    render() {
        if (this.state.isEditing) {
            return <PageEditor
                {...this.props}
                onCancel={this.onCancel.bind(this)}
                />;
        }

        return <PageView
            {...this.props}
            onPageEdit={this.onEdit.bind(this)}
            />;
    }

    onEdit() {
        this.setState({
            "isEditing": true
        });
    }

    onCancel() {
        this.setState({
            "isEditing": false
        });
    }
}

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:

class PageEditor extends Component {
    constructor(props) {
        super(props);

        this.state = {
            "changed": false
        };

        this.bind(
            "onCancel",
            "onUpdate"
        );
    }

    isChanged(next, previous) {
        return JSON.stringify(next) !== JSON.stringify(previous)
    }

    componentWillReceiveProps(props) {
        this.setState({
            "changed": this.isChanged(props, this.props)
        });
    }

    render() {
        return <div>
            <input
                type="text"
                name="title"
                value={this.props.title}
                onChange={this.onUpdate...

Summary


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.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React Components
Published in: Apr 2016Publisher: ISBN-13: 9781785889288
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt