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 4. Styling and Animating Components

In the last chapter, you learned how persist pages even after reloading the page or restarting the browser. We're at the point now where this could start to be a useful system for us. Unfortunately, it still looks rough and unstyled.

That's because, up until now, we've almost completely ignored styles in our components. In this chapter, we will change all that!

You will learn how to add custom styles and class names to component elements. We'll add animations to new and old components. We'll even learn how to combine the two to create highly reusable styles and animation.

Adding new pages


So far, we are able to change and remove pages from our content management system. We ended the last chapter by seeding our local storage with a serialized array, so we could see it in action. Let's take a step back and make a way to create new pages through the interface.

First, we'll add an insert method and update the constructor method of Backend:

constructor() {
    super();

    var pages = LocalStore.get("pages", []);

    this.id = 1;

    this.pages = pages.map((page) => {
        page.id = this.id++;
        return page;
    });
}

insert() {
    this.pages.push({
        "id": this.id,
        "title": "New page " + this.id,
        "body": ""
    });

    this.id++;

    LocalStore.set("pages", this.pages);

    this.emit("update", this.pages);
}

The page id values aren't really important to us outside the context of our React components. So, it's fine to regenerate them as the pages are loaded from local storage. We keep track of the internal id value, so new...

Adding styles to components


There are a number of ways we could improve the appearance of our components. Let's take the PageView component, for example. What would make it better? Perhaps if we increased the font size and used a sans serif font, the titles would be clearer to read. Perhaps we could increase the margin around each page.

There are a few different ways to style our components. The first is by adding styles inline to the render method in PageView:

render() {
    var rowStyle = this.props.rowStyle || {
        "fontSize": "18px",
        "fontFamily": "Helvetica"
    };

    var labelStyle = this.props.labelStyle || {
        "whiteSpace": "nowrap"
    };

    var buttonStyle = this.props.buttonStyle || {
        "margin": "0 0 0 10px",
        "verticalAlign": "middle",
    };

    return <div style={rowStyle}>
        <label style={labelStyle}>
            {this.props.title}
        </label>
        <button
            style={buttonStyle}
            onClick...

Changing and reverting


Now we can style our edit form. Let's replace the modification indicator (asterisk) with a button that will simulate the save action:

constructor(props) {
    super(props);

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

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

render() {
    var cancelButtonStyle = null;
    var saveButton = null;

    if (this.state.changed) {
        cancelButtonStyle = this.props.cancelButtonStyle || {
           "margin": "0 0 0 10px"
        };

        saveButton = <button
            onClick={this.onCancel}>
            save
        </button>
    }

    return <form>
        <div>
            <input
                type="text"
                onChange={this.onUpdate}
                name="title"
                value={this.props.title}
                />
        </div>
        <div>
            <input
                type="text"
                onChange...

Animating new components


At the moment, new pages are just appearing. There's no subtle animation to ease them in. Let's change that!

We will use a new React component for this, and we can find it in the add-ons build of React. Go back to the React scripts you downloaded in the first chapter and replace all references to react.js with react-with-addons.js.

This gives us access to a new component called CSSTransitionGroup:

render() {
    var itemStyle = this.props.itemStyle || {
        "minHeight": "40px",
        "lineHeight": "40px",
        "fontSize": "18px",
        "fontFamily": "Helvetica"
    };

    return <div>
        <div>
            <button
                onClick={this.onInsert}>
                create new page
            </button>
        </div>
        <ol>
            <React.addons.CSSTransitionGroup
                transitionName="page"
                transitionEnterTimeout={150}
                transitionLeaveTimeout={150}>
  ...

Working with CSS transitions


It's a great time to talk about CSS transitions. We have used them to fade and slide new Page components in from the left. If you're unfamiliar with how they generally work, the code might be confusing and difficult to change.

There are a few things you should know. The first is that you can transition individual CSS properties or all of them at once:

.background-transition {
    background-color: red;
    font-size: 16px;
    transition-property: background-color;
}

.background-transition:hover {
    background: blue;
    font-size: 18px;
}

In this example, we only want to transition the background color. The font size will immediately jump from 16px to 18px. Alternatively, we can transition all CSS properties:

.all-transition {
    transition-property: all;
}

We've already seen transition duration, albeit briefly. We can use ms or s as units for these:

.background-transition {
    transition-duration: 1s;
}

Then there are timing functions. These control how the animation...

Organizing styles with Sass


Style sheets are a great alternative to inline component styles. CSS is wonderfully expressive as a language for finding and applying visual characteristics to elements.

Unfortunately, it also has drawbacks. The biggest drawback to CSS is that all styles are in global scope. Some styles are inherited, and styles applied to elements often collide (and cancel each other out).

In small doses, the collisions are avoidable or manageable. In large doses, these collisions can cripple productivity. As a stop-gap, CSS supports the !important keyword. This often leads to ugly hacks, as everyone wants their styles to be the most important.

In addition to this, common values need to be repeated. Until recently, CSS didn't even support calculated values. If we wanted an element to have an absolute width (for example) in relation to other elements, we had to use JavaScript.

These are some of the problems Sass aims to solve. It's a CSS superset language (CSS + other features), so...

Alternatives


There are a few other ways in which we can style and animate React components, and they all deal with the issue in subtly different ways.

CSS modules

CSS modules allow you to define styles that only apply in a local context to individual elements. They look like regular CSS styles, but when they're applied to components, they are altered so that the class names given to components are unique. You can read more about CSS modules at http://glenmaddern.com/articles/css-modules.

React style

React style is a way of creating inline styles as slightly enhanced objects. It lacks support for a few common CSS selectors, but does a good job otherwise. You can read more about it at https://github.com/js-next/react-style.

Summary


In this chapter, you learned how to style React components great and small. We used inline styles, CSS style sheets, and even Sass style sheets. You also learned how to animate child components in and out of view using CSS transitions.

Finally, we looked briefly at a couple of alternative technologies, which do the same things we did in this chapter but in slightly different ways. You may prefer one of these methods over all the others, but what is important is to recognize that there are many methods we can use to style and animate components.

In the next chapter, we will put all these skills to use as we dive into material design. There's lots of styling and animation to come!

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