Posts

,

15 Blogs Every Javascript Developer Should Follow in 2020

I’ve been following the most interesting JavaScript blogs quite for a while now (this is a part of my job running https://weekendjs.com/). There are many of them. More than you might think. There are blogs started more than ten years ago, and there are relatively new ones. Some bloggers are JavaScript superstars, and others are regular engineers like you and me. Some blogs are focused on a particular ecosystem (say Angular or React, or Vue), while others are rather general.

The exciting thing is that the number of good blogs with really robust material keeps growing from one year to another. It is a promising trend, which hopefully will continue.

A few words about who makes it into the list: only the bloggers who write relatively often (at least once per month). Those are all personal blogs, not hubs, companies, etc. And of course, the main metric is the quality of the material.

OK, enough words. Please welcome, in no particular order, the top 15 blogs a JavaScript developer should follow in 2018.

2ality

The author of the “Exploring ES6” book, Dr. Axel Rauschmayer is long known for his deep and comprehensive articles. They are always well-structured and tend to cover the topics in every detail. Usually he writes about ES6/7/8 features and how to use it, but recently, for example, he did a series of articles on ReasonML, which is a hot new JS-transpilable language from Facebook.

David Walsh

David Walsh is an engineer who works at Mozilla from Madison, Wisconsin. David writes regularly (several times per month). His posts are about web development in general. Usually, these are small, understandable pieces for a broad audience on JavaScript’s new features, Node, and more.

Reginald Braithwaite

Reginald “raganwald” Braithwaite, is the author of brilliant “JavaScript Allongé,” one of my favorite JavaScript books. If you haven’t read it, go ahead and do it. Seriously, it’s a pure pleasure, I promise. As you might expect, he writes a lot on functional-related topics. His articles are probably not for beginners and instead aimed at a more experienced audience.

Michael Herman

Michael Herman is a developer and public speaker. He writes about a lot of stuff such as Python, Docker, etc. Technically, I could leave him out of this list. But his write-ups on JavaScript and related material are extremely practical and helpful, so I just can’t leave out his brilliant blog.

Addy Osmani

I’m not sure I need to introduce Addy Osmani. He is a Chrome core developer, a web performance evangelist, and a public speaker. You probably use libraries he has written on a daily basis; just check his GitHub. He also wrote the very popular “Learning JavaScript Design Patterns” book. In his blog though, he writes a lot on Progressive Apps and is one of the core contributors to the concept.

Ponyfoo

This one is easily recognizable by the iconic pixelated image of a unicorn. The author writes lots about new ECMAScript features, in particular modules, and is (as you might expect) in the middle of writing a book about modules.

Dave Ceddia

Dave’s first post dates back to 2015. And it was about Angular 2 (yeah, can you believe it? Time runs so fast). In 2017, though, it seems as if he changed his preferred framework and started writing more on React. He’s also an author of a lovely little book called “Pure React” which is aimed at starters.

Todd Motto

Speaking of Angular, it’s surprisingly difficult to find robust material on the topic. It’s understandable, perhaps, since React seems to be a lot more fun to write about. Well, at least we have this guy. Todd writes a lot on connected topics (TypeScript, NGRX), speaks at the conferences and also does courses. He’s easily the best individual Angular blogger out there.

Tyler McGinnis

Tyler McGinnis is the author of many thorough React courses. So, as you might expect, he also writes a lot about React both Web and Native. His blog also contains a lot of video materials, which are a joy to watch.

John Papa

John Papa is a developer advocate, public speaker, and of course, a blogger. He also authored several courses on for Pluralsight. He used to write a lot on Angular, especially Angular 1, but it seems he’s more into Vue now. If you’re interested in this React alternative you should follow this guy.

Valentino G.

This guy writes a lot of different topics, including Django and Node. Most often he writes about React and friends.

Ben Nadel

I didn’t know about this one until recently, but now it’s easily one of my favorite JavaScript blogs. My favorite part is that he writes a lot about UX and its intersections with JavaScript. Highly recommend it!

Bram Van Damme

It’s interesting that lots of bloggers are from Europe. Like Bram, who is an engineer from Belgium. He writes about JavaScript and also more in general about the web and web development.

Ivan Akulov

Ivan writes about React and Webpack, and also in general about different optimizations you’ll need to do as a web developer. His write-ups are highly practical, and may not suit the beginners.

Robin Wieruch

Robin works in Berlin. He writes a lot (and quite often) about React and friends. But also (and that’s what makes him interesting) he writes about stuff like AI and machine learning. There aren’t a lot of places where you can read articles like “A Web Developer’s Guide to Machine Learning in Javascript” or “Neural Networks in Javascript.” If you’re interested in those topics, you definitely need to follow Robin.

I hope you liked this list. Now go ahead and add them to your preferred RSS reader as I did and enjoy the perpetual flow of the best articles from the JavaScript world!

, ,

AirNYT: Building the Map and Markers Interactivity

This tutorial is a part of a larger tutorial series on cloning the Airbnb map/cards interface to be able to explore the last 7 years of New York Times travel recommendations. The short name for this app/series is AirNYT.

In this part of the tutorial, we will continue building out the various components that make up this map and cards interface.

This specific tutorial will cover how to turn this:

http://nytrecsalaairbnb.surge.sh

…into this:

http://airnyt.surge.sh

To do this, I’ll show you how I built out the following functionality:

  • A carousel slideshow on each card for each location
  • A interactive map with map markers that can be hidden/shown with a toggle switch
  • Hover events on cards that change styling on the map markers

There’s a lot to cover in this tutorial and I’ll try to skip as much boilerplate, yarn installations, and styling as possible when I’m showing how the different parts are coded. If you’d like to see the complete code, you can do so here:

https://github.com/kpennell/airnyt

A carousel slideshow on each card for each location

As you’ve likely seen, Airbnb property listings have these really elegant slideshows on each property:

These let you get the jist of the place without going to that page. To recreate that functionality in the AirNYT app, I’m going to use the React-slick library. This is a React version of the very popular Slick Carousel library.

The react-slick API was fairly straightforward to use. I created a separate CardCarousel component to house it. The component is a simple Slider component that rotates through different material-ui CardMedia images from my data.

class CardCarousel extends React.Component {
  render() {
    const { classes, location } = this.props;

    return (
      <div>
        <Slider {...settings}>
          <div>
            <CardMedia
              component="img"
              className={classes.media}
              image={location.image1}
            />
          </div>
          {location.image2 && (
            <div>
              <CardMedia
                component="img"
                className={classes.media}
                image={location.image2}
              />
            </div>
          )}
          {location.image3 && (
            <div>
              <CardMedia
                component="img"
                className={classes.media}
                image={location.image3}
              />
            </div>
          )}{" "}
        </Slider>
      </div>
    );
  }
}

To mimic the chevron right and left arrows from the Airbnb slider, I put these custom arrows in using material-ui icons:

function SampleNextArrow(props) {
  const {
    className,
    style,
    onClick
  } = props;
  return (
    <ChevronRight
      className={className}
      style={{
        ...style,
        display: "block",
        color: "white",
        fontSize: "3em",
        right: "9px",
        zIndex: 1
      }}
      onClick={onClick}
    />
  );
}
function SamplePrevArrow(props) {
  const {
    className,
    style,
    onClick
  } = props;
  return (
    <ChevronLeft
      className={className}
      style={{
        ...style,
        display: "block",
        color: "white",
        fontSize: "3em",
        left: "9px",
        zIndex: 1
      }}
      onClick={onClick}
    />
  );
}

Within the settings, I can tell the Slider component that I’d like to use these arrow components:

const settings = {
dots: true,
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
nextArrow: <SampleNextArrow />,
prevArrow: <SamplePrevArrow />,

And voila, I have working sliders on all of my cards:

The one caveat I’d share about these sliders is that they definitely slow down the interface. We saw how fast React-virtualized made loading the 380+ cards in the last blog post. But now, each card is loading 3 images, and the lag is noticeable. To solve this, I’d recommend trying out some sort of virtualized or windowed slider that only loads the image when someone opens it or slides to it. But that being said, as long as we’re paginating these results (card listings), the lag shouldn’t be too terrible.

An interactive map with map markers

Maps are perhaps the original data visualization. For spatial or location data, a map is indispensable for visualizing the data. Airbnb has a really well-designed map that can be toggled with a simple switch and we can mimic this fairly easily.

But first, we need a mapping library! The gargantuan React ecosystem offers many options, both in terms of how they are loaded, how they are interacted with, and which tiles (e.g. Google, OSM) get loaded. I’ve tried several and have kept coming back to google-map-react. This library allows React developers to load any component as a marker on a Google map. I like how this library feels like a react-specific way of doing things (a la ‘everything is a component’) and it seems to get out of my way. If you wish to tweak things on the actual Google Maps JavaScript API, google-map-react gives you a simple API to do so.

My MapAndMarkers component is fairly straightforward. I’ll explain how it works after this code snippet:

class MapAndMarkers extends React.Component {
  static defaultProps = {
    center: {
      lat: 30,
      lng: -30
    },
    zoom: 0
  };
  render() {
    const {
      classes,
      locations,
      hoveredCardId,
      pageid
    } = this.props;
    let MapMarkers = locations.map(
      (location, index) => {
        return (
          <MapMarker
            key={location.id}
            lat={location.lat}
            lng={location.lng}
            name={
              location.location_name
            }
            pageid={location.pageid}
            hoveredCardId={
              hoveredCardId
            }
          />
        );
      }
    );
    return (
      <div
        style={{
          width: "100%",
          height: "100%"
        }}
      >
        <GoogleMapReact
          bootstrapURLKeys={{
            key:
              "AIzaSysBBvQLsewI7BPpXln_Jzl_tIUVsH1f775C7GXM",
            v: "3.31"
          }}
          defaultCenter={
            this.props.center
          }
          defaultZoom={this.props.zoom}
          hoverDistance={20 / 2}
          options={createMapOptions}
        >
          {MapMarkers}
        </GoogleMapReact>
      </div>
    );
  }
}

GoogleMapReact is the primary google-map-react component here, and it needs some props and children to work. The required props include the API keys and center and zoom. Center and zoom tell the map which tiles to load. The options prop allows for controlling the aforementioned underlying Google JavaScript API. Things like panning, zooming, controls, etc. get controlled with this object. hoverDistance allows for controlling how far/close to a marker counts as mouse hovering.

To create the {MapMarkers} children, I .map over the locations array prop (my cards/locations data) and pass things like key, lat, and lng as props to the MapMarkers(s). These props tell GoogleMapReact where to render these components/points/markers. I’ll explain the hoveredCardId prop within the context of my MapMarker component.

My MapMarker component is fairly straightforward. The goal was to mimic the plain white tooltips that Airbnb uses:

I used CSS arrow please to create the CSS for this component and used this CSS to React tool to ‘JSSify’ my CSS. There are a variety of nifty React tooltip libraries out there, but I went this route to keep the map fast and have one less dependency.

class MapMarker extends React.Component {
  render() {
    const {
      classes,
      pageid,
      hoveredCardId
    } = this.props;

    return (
      <div
        className={classes.markerParent}
      >
        <span
          className={classNames(
            classes.tooltips_span,
            pageid == hoveredCardId &&
              classes.niftyHoverBackground
          )}
        >
          {this.props.name}
        </span>
      </div>
    );
  }
}

When someone hovers on a Card in the list, I want the MapMarker background to turn purple, like Airbnb does:

To achieve this, I used the classNames library to toggle the class with the background color. So, if the id from the card (that is being hovered upon) is equal to id on the marker, the style changes. To set this id, I setup some functions to be called by mouse events:

// LocationCards.js

<Card className={classes.card} onMouseEnter={e => this.props.c(location)} onMouseLeave={e => this.props.resetCardMarkerHover()} >

setCardMarkerHover is a straightforward function that updates the state variable of hoveredCardId according to the card that is being hovered upon.

// LocationsGrid.js

setCardMarkerHover = location => {
  this.setState({
    hoveredCardId: location.pageid
  });
};

I know I’m skipping some of the steps here but please read through the code if you’d like to see how the state/props variables work here.

Toggle-able Map

Like I mentioned, I really like how Airbnb lets users toggle the map.

Sometimes you want a map and sometimes you just want a grid of cards (and more screen real estate). To recreate this functionality, I put a toggle switch in my FilterBar, like so:

import Switch from "@material-ui/core/Switch";
<FormGroup row>
  <FormControlLabel
    control={
      <Switch
        checked={this.props.mapShowing}
        onChange={
          this.props.toggleMapShowing
        }
        classes={{
          switchBase:
            classes.AirBnbSwitchBase,
          bar: classes.AirBnbBar,
          icon: classes.AirBnbIcon,
          iconChecked:
            classes.AirBnbIconChecked,
          checked: classes.AirBnbChecked
        }}
      />
    }
    label="Show Map"
    labelPlacement="start"
  />
</FormGroup>;

This switch is on or off depending on the prop mapShowing. When it gets toggled, it calls the function toggleMapShowing. Fairly straightforward! Now, within my LocationsGrid component, I toggle the map like so:

{
  this.props.mapShowing && (
    <div className={classes.mapDiv}>
      <MapAndMarkers
        locations={locationsSlicedDownOnPage}
        hoveredCardId={this.state.hoveredCardId}
      />
    </div>
  );
}

The state variable mapShowing and the toggleMapShowing function live within App.js.

Getting the map to push the list over was achieved using flex-box (how did we go without it?!) and inline-block:

mapDiv: {
height: "100%",
width: "65%",
display: "inline-block",
position: "sticky",
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
[theme.breakpoints.down("sm")]: {
display: "none"
}
},
listGridDiv: {
overflow: "auto",
height: "85vh",
[theme.breakpoints.down("sm")]: {
justifyContent: "center",
}
},
parentDiv: {
display: "flex",
justifyContent: "space-between",
height: "100%",
overflow: "hidden"
},

This allows the map to kindly push its way onto the scene, and the flexbox grid of cards responds accordingly. The last thing I’ll point out here is that the cards are flex-start aligned when the map is in and centered when the map is hidden. This makes for a more attractive ui and is achieved with this simple ternary on the parent <Grid>:

justify={this.props.mapShowing ? "flex-start" : "space-evenly"}

I didn’t do it here, but the next step would be to mimic the ✓ vs. X in the AirBnb toggle switch:

I’m fairly confident a bit of digging into the various props of the material-ui Switch component would allow for this.

This tutorial will be continued in the next section, where we will cover building:

  • Working Pagination to make exploring the data easier/faster
  • A popup year filter that allows users to show NYT data by year
  • Text/Search Filtering to allow for string queries of the data
  • A responsive menu
  • General responsible responsiveness to make this app mobile-friendly

Note: This open source map got put into action for this Oaxaca Hiking Map Website. It has also been favorited over ten times on Github.

, ,

Using Mobx + Firebase to build a Twitter Clone

In this tutorial I’ll be showing you how to create a very Twitter Clone using React and Firebase. MobX will be used as the data store for Firebase data. Here’s what the final output is going to look like:

MobX-Firebase Twitter Clone

Firebase Setup

In order to not bog us down in Firebase setup, this tutorial will assume that you already have an existing Firebase project created in the Firebase Console. If not, go ahead and create one. Once you have a project, go to the database section and under the rules tab add the following:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This sets read and write permissions of your database to public. This means you don’t need to authenticate later on in order to gain access the database. This is good for quickly getting started with something, but not for production apps. Be sure to change this later!

Project Setup

Clone the create-react-app-mobx project. This allows you to easily create a React Project which has already the MobX toolset built into it (the original create-react-app doesn’t support all MobX features yet).

git clone https://github.com/mobxjs/create-react-app-mobx.git react-firebase-mobx-twitter-clone

Next, open your package.json file and add the following:

"mobx-firebase-store": "^1.0.3",
"react-timeago": "^3.2.0",
"chance": "^1.0.6",
"slugify": "^1.1.0",
"twitter-text": "^1.14.3"

Here’s a breakdown of what each package does:

  • mobx-firebase-store – used for storing Firebase data in MobX maps. This uses Firebase-nest as a peer dependency to subscribe to changes in a Firebase store.
  • react-timeago – used for generating a human-friendly text based on a timestamp.
  • chance – used for generating a random name to be assigned to the current user.
  • slugify – used for making the random name URL-friendly.
  • twitter-text – contains utility functions for working with twitter text. Things like counting the remaining text and converting URL’s into links.

Execute npm install to install all the packages. Once that’s done, you can run npm start to serve the project for development. You can access https://localhost:3000 on your browser to view the project.

Creating the Main Component

Before moving on, delete everything inside the src folder of the project. By default it contains a demo project that uses MobX to implement a counter app. We don’t really need those so you can go ahead and delete them.

Create an index.js file. This is where you supply your Firebase database URL and render the main app component which you’ll be creating later:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

const config = {
    databaseURL: 'https://{YOUR_FIREBASE_PROJECT_NAME}.firebaseio.com',
};

ReactDOM.render(
  ,
  document.getElementById('root')
);

Next, create an App.js file. This is where you import the TweetList component we’ll build that serves as the component that the user will interact with, and the TweetStore store which contains the code for connecting, and saving/reading data from Firebase.

import React, { Component } from 'react';
import TweetList from './TweetList';
import TweetStore from './TweetStore';
import './index.css';

class App extends Component {

  componentWillMount() {
    this.store = new TweetStore(this.props.config); //create a new instance of the store by passingin the Firebase config
  }

  render() {
    return (
      

MobX-Firebase Twitter Clone

); } } export default App;

Creating the TweetList Component

Now we’ll create the TweetList.js file. At the very top, import all the libraries and components that you need. You’ll see how each of these will be used later so we won’t cover what each one does here.

import React, { Component } from 'react';

import { observer } from 'mobx-react';
import { createAutoSubscriber } from 'firebase-nest';

import Chance from 'chance';
import slugify from 'slugify';
import TimeAgo from 'react-timeago'
import twitter_text from 'twitter-text';

const tweet_limit = 140;
var ch = new Chance();

Next, create the Tweetlist component. Initialize the state as well as the functions inside the constructor.

class TweetList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      tweet: '', //the user's tweet text
      username: slugify(ch.name()),
      loading: false, //whether the Firebase data is currently loading or not
      remaining: tweet_limit //number of characters allowed for each tweet
    };
    this.updateText = this.updateText.bind(this); 
    this.submitTweet = this.submitTweet.bind(this); 
  }
  ...
}

The render() method uses the getTweets() method from the store. You’ll be creating this later, for now know that everytime someone makes a change to your Firebase database, the component gets re-rendered. If the Firebase data becomes available, the textarea for entering the tweet and the list of tweets gets rendered.

render() {
  const tweets = this.props.store.getTweets();
  if (!tweets) {
    return 
Loading tweets...
} return (
{this.state.username}
{this.state.remaining}
{tweets.keys().reverse().map(messageKey => this.renderTweet(messageKey, tweets.get(messageKey)))}
); }

Here’s the function for rendering each tweet:

renderTweet(key, tweet) {
  return (
    
@{tweet.username} -
); }

The function for updating the state of the current tweet text and remaining count:

updateText(evt) {
  let tweet = evt.target.value
  let remaining = tweet_limit - twitter_text.getTweetLength(tweet);
  this.setState({
    tweet,
    remaining
  });
}

The function for saving the tweet in Firebase:

submitTweet() {
  this.props.store.createTweet({
    username: this.state.username,
    timestamp: new Date().getTime(),
    text: this.state.tweet 
  });

  this.setState({
    tweet: '',
    remaining: tweet_limit
  });
}

Next, you need to define the getSubs() and subscribeSubs() function. The naming is relevant because the Firebase-nest library rely on these two functions. getSubs() returns the array of subscriptions while subscribeSubs() performs the subscription and returns the function for unsubscribing from the Firebase data.

getSubs(props, state) {
  return props.store.allTweetsSubs();
}

subscribeSubs (subs, props, state) {
  return props.store.subscribeSubs(subs);
}

Finally, you use the createAutoSubscriber() function to subscribe and observe to Firebase data. This function uses the getSubs() and subscribeSubs() functions that you defined earlier in order to subscribe to Firebase data and propagate the changes in the store. It will then return the function that requires a Reactive component to be passed in. We can turn our component into a Reactive one by wrapping it in MobX’s observer() function. This ensures that any data that is used for rendering the component forces a re-rendering when it’s updated. If you don’t set your component as an observer, it won’t re-render when the current user or someone else posts a new tweet.

export default createAutoSubscriber()(observer(TweetList));

Creating the Store

We shall now create out Mobx store. Create a TweetStore.js file. This serves as the store for the TweetList component. It contains the methods for saving and fetching data from Firebase.

Start by importing firebase and mobx-firebase-store. firebase is the official Firebase JavaScript library for working with Firebase. This allows you to connect to Firebase. The mobx-firebase-store library provides a bridge between the Firebase library and the MobX library. It allows you to subscribe to Firebase data through the use of firebase-nest subscriptions. This makes the data flow into MobX’s observable maps.

import Firebase from 'firebase';
import MobxFirebaseStore from 'mobx-firebase-store';

Define the property in which the array of tweets are stored:

const tweets_subkey = 'tweets';

Here’s what it looks like in the Firebase console:

Firebase database subkey

Create the store. Inside the constructor, connect to Firebase and create the store. MobXFirebaseStore accepts a reference to a Firebase database as its argument. Right below that, call super(store.fb) to make the store available inside the class via this.

export default class TweetStore extends MobxFirebaseStore {

  constructor(config) {
    const fbApp = Firebase.initializeApp(config);
    const store = new MobxFirebaseStore(Firebase.database(fbApp).ref());
    super(store.fb);
  }
  ...
}

allTweetsSubs() as you’ve known earlier, returns an array of subscriptions. In this case you only want to subscribe to a single subkey (tweets) and you want its data to be returned as a list (asList: true). Basically, it’s used to specify the subkey in your Firebase database that you want to subscribe to.

  
allTweetsSubs() {
  return [{
      subKey: tweets_subkey,
      asList: true
  }];
}

createTweet() uses Firebase’s push method to push the tweet object into the array. This creates a new item in the tweets array in Firebase which then triggers the subscriber to update the list of tweets for all the connected clients.

createTweet(tweet) {
  this.fb.child(tweets_subkey).push(tweet);
}

getTweets() returns the collection of tweets:

    
getTweets() {
  return this.getData(tweets_subkey);
}

resolveFirebaseQuery() is used for customizing the query used for fetching Firebase data. Here, the results are ordered according to their timestamp and only the 10 most recent tweets are being fetched. That said, Firebase still returns the records in ascending order that’s why you had to call reverse() on the TweetList component earlier to reverse the ordering.

  
resolveFirebaseQuery(sub) { 
  return this.fb.child(tweets_subkey).orderByChild('timestamp').limitToLast(10);
}

Add the Styles

Open the public/index.html file and add the following inside the <head>:


This uses picnic.css to add some default styling to make the project look good.

Next, create a src/index.css file and add the following:

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

.tweets {
    margin-top: 30px;
}

.tweet {
    padding: 20px;
}

Conclusion

That’s it! In this tutorial you’ve learned how to use MobX to act as a data store for your Firebase data. As you have seen, using Firebase with MobX doesn’t completely change the way you interact with Firebase so you can still use your existing knowledge of the Firebase API. You can check out the code used in this tutorial in this Github repo.

, , , , ,

Where Did Vue.js Come From?

Vue.js’s popularity has been climbing pretty fast. It has about 3/4 the number of stars on Github as React, and more than double the stars of Angular. The watchers and forks are also pretty comparable. And the while Vue.js hasn’t nearly caught up yet, you can see a definite trend of relatively rapid growth on Google Trends that is comparable to the growth of React and Angular earlier in their lives.

graph

Angular is still on top, but Vue.js is rising quickly

There needs to be a reason that Vue.js is growing rapidly, especially when the JavaScript framework ecosystem is already filled with plenty of great frameworks. Vue.js doesn’t truly offer anything that other frameworks don’t already have, but it does bring together features from other frameworks in a unique way that may be a better combination. Which of these features did Vue.js glean from other frameworks, and from which ones?

Component-Based

“Component-based” means that the framework is based around creating, composing, and nesting user interface building blocks called components. These components encapsulate everything to do with themselves rather than moving the logic out to a controller or something similar. Components go beyond view objects because they because they can be used directly in the templates as if they were HTML elements:

 

Some Title

Hello

 

React is likely the primary source of inspiration for Vue.js in this area, though you could argue that Polymer and/or Web Components should be considered the inspiration here. I lean toward React primarily because Polymer is designed to actually create custom elements to be used directly in the HTML, whereas React and Vue.js use their components as if they were custom elements only in their templates (JSX in React’s case) and use the rendering engines and template compilers to only give the browser HTML elements that it already knows.

In the end, though, it doesn’t really matter who the idea was stolen from. What matters is that the declarative nature component-based systems are far simpler to use and compose than the imperative, old-school views and sub-views that came with Backbone.js and similar MV* frameworks.

Directives

Directives are a means of control flow and DOM manipulation that are built into the templates and look like HTML attributes. For example:

    • {{ item.message }}

 

 

The v-for attributes is a directive that loops through items so they can all be displayed in li elements. Angular and Aurelia do very similar things. In Angular it would look like this:

    • {{ item.message }}

 

 

And Aurelia looks like this:

    • ${ item.message }

 

 

If you don’t have this kind of control capability embedded in the template syntax, the code becomes more difficult to read because you need to switch back and forth between the template syntax and the JavaScript’s syntax. Once again, the code is becoming more declarative instead of imperative.

Single, HTML-Based Component File

I wrote an article entirely about Vue’s Single File Components and the benefits they provide. It turns out, though, that Vue.js wasn’t the originator of this idea, at least not entirely. Vue.js stole this from Polymer/Web Components. Right on Polymer’s home page, halfway down the page you’ll find an example that looks remarkably similar to a Vue.js Single File Component:

<dom-module id="contact-card">
  <style>...</style>
  <template>
    <content></content>
    <iron-icon icon="star" hidden$="{{!starred}}"></iron-icon>
  </template>
  <script>
    Polymer({
      is: 'contact-card',
      properties: {
        starred: Boolean
      }
    });
  </script>
</dom-module>

Of course, Vue.js goes beyond this by allowing you to use alternative languages for the CSS (Sass, Less, Stylus, CSS Modules), HTML (Pug), and JavaScript (TypeScript, CoffeeScript) due to the required build step. The combination of all of these languages and technologies into a single file may be one of the greatest features for component-based frameworks due to being able to congregate everything related to the component into a single file for better maintenance.

Limited Functionality for Greater Flexibility

Vue.js in and of itself is focused around rendering reactive and interactive user interfaces. It offers little in the way of structure or architecture. This is completely on purpose and it follows pretty much the same pattern as React in this regard. Like React, it lets other libraries handle the extra functionality, such as routing and more advanced, centralized state management. Unlike React, though, Vue.js provides officially supported libraries for some of these things, rather than leaving them up to third parties.

By removing this functionality from the core framework, you get a smaller file size and the flexibility to use other libraries if you want to. The trade-offs are that there are more choices to make and there isn’t necessarily 1 right way to do something because everyone is using something different. By officially supporting vuex and vue-router, though, these trade-offs are mitigated.

Conclusion

Everything is based off of something that already exists, and Vue.js is definitely no exception. Despite having nothing new, though, Vue.js’s growth and popularity most likely came about because it stole and combined many of the best concepts from the other frameworks out there and kept out many of the things that cause headaches for developers.

, ,

Build a Camping Weather App with React, Redux and Thunk Middleware

Let’s face it, while it’s fun to write applications from scratch, a lot of software development work involves working with existing code. In this post, we are going to learn how to add a feature to an existing React/Redux app. Following on our previous articles in <list filtering with react/redux> and <component interactivity with react/redux>, we will add a feature to get a weather forecast estimate to help us figure out when is the best time to visit crater lake. In addition, since we are querying an API, we will be learning how to use async actions to retrieve and display the weather.

Here’s an outline of the process we will be following

  1. Adding a date selector component to let the user pick a date for getting the weather.
  2. Getting weather information from the <DarkSky api>
  3. Identifying where and when to update state to incorporate our new weather feature
  4. Handling state changes with async interfaces

Check out the final product on Heroku and get the code on Github.

finished image.png

Adding a date selector

Using the react-datepicker module we’ll create a new WeatherDatePicker component to show the date picker and the forecast results. When the user loads the page they will see “Select a date…”:

date picker.png

After a date is selected, the forecast will be displayed:

date picked.png

Taking a look at the render method in WeatherDatePicker.jsx:

render() {

 return (

 <div>

 Travel Date:

 <DatePicker

 placeholderText="Select a date..."

 selected={this.props.selectedDate}

 dateFormat = "YYYY-MM-DD"

 onChange={(selectedDate) => {

 let newDate = this.checkDate(selectedDate)

 if (newDate) {

 this.props.fetchWeather(this.checkDate(selectedDate), this.props.currentLat, this.props.currentLong)

 }

 } }/>

 Forecast: {this.props.weatherSummary}

 </div>

 );

}

When the DatePicker is opened and a date is selected, firing the onChange event, we first check the date to make sure it is in the future:

checkDate(selectedDate) {

 if (selectedDate.isBefore(this.props.currentDate)) {

 alert("Please pick a date in the future.")

 return undefined

 }

 else {

 return selectedDate.format("YYYY-MM-DD")

 }

}

The DatePicker module uses moment.js for the date object. We can use moment’s isBefore method to compare two moment objects, and display an alert if the user picks a date in the past. If the render method receives a valid result, it calls the delegate fetchWeather, passing along the selected date, to retrieve the weatherSummary.

Now we will add the WeatherDatePicker component and the DarkSky attribution graphic to CampFilterApp.jsx:

render() {

 return (

 <div className="container">

 <div><a href="https://darksky.net/poweredby/"><img src="https://darksky.net/dev/img/attribution/poweredby.png" style={{ width: 100 }}/></a></div>

 <Jumbotron>

 <h1>Crater Lake Camping</h1>

 </Jumbotron>

 <br></br>

 <CampFilterList {...this.props}/>

 <br></br>

 <WeatherDatePicker {...this.props}/>

 <br></br>

 <CampMapContainer {...this.props} />

 </div>

 )
};

While we are working with components, let’s also update the Redux store to include the thunk middleware that we’ll be using for the next steps. We just need to add thunkMiddleware to our createStore call. In index.js:

import thunkMiddleware from 'redux-thunk'

const store = createStore(reducer, applyMiddleware(

 thunkMiddleware

))

Adding state and async actions for the weather feature

Now that we have a component to display the weather, lets look into the associated actions and state needed to do the work.

For the weather feature, the following fields are added to the state in index.js and set as props in CampFilterApp.jsx:

currentDate: today,

weatherSummary: "",

currentLat: 42.9456,

currentLong: -122.2,

selectedDate: undefined

The DarkSky API needs a position and date to retrieve the weather. Since our app is localized to Crater Lake we’ll use those coordinates to retrieve the weather. Don’t forget to convert these new state variables to props to send down to the WeatherDatePicker component in CampFilterApp.jsx:

function mapStateToProps(state) {

 return {

...

 weatherSummary: state.get('weatherSummary'),

 currentDate: state.get('currentDate'),

 currentLat: state.get('currentLat'),

 currentLong: state.get('currentLong'),

 selectedDate: state.get('selectedDate')

 };

}

To query the API and update the selectedDate and weatherSummary variables we will use thunk middleware and fetch as described in this article from the Redux docs.

To handle an async action, we will split the API call into request and receive actions. Our request action, REQ_WEATHER, will update the selectedDate to the value passed from the DatePicker and weatherSummary to “Loading…” to let the user know the weather info is loading. From action_creators.js:

export function reqWeather(weatherDate) {

 return {

 type: 'REQ_WEATHER',

 weatherDate

 }

}

And the corresponding function in reducer.js:

function reqWeather(state, weatherDate) {

 return state.merge(Map({

 'weatherSummary': "Loading...",

 'selectedDate': weatherDate

 }))

}

For the receive action, RECV_WEATHER, we add a response field to our state to hold the JSON returned by the DarkSky API:

export function recvWeather(weatherDate, result) {

return {

type: 'RECV_WEATHER',

weatherDate,

response: result

}

}

The corresponding method in reducer.js for parsing the API response into the weatherSummary field:

function recvWeather(state, weatherDate, result) {

 let content = ""

 try {

 let tempMax = result.daily.data[0].temperatureMax

 let tempMin = result.daily.data[0].temperatureMin

 let summary = result.daily.data[0].summary

 content = summary + " High: " + Math.ceil(tempMax) + " Low: " + Math.ceil(tempMin)

 }

 catch (err) {

 console.log("couldnt get weather summary: " + err)

 }

 return state.merge(Map({

 'weatherSummary': content

 }))

Alright, at this point you may be wondering “This is great and all, but where’s the part where we actually query the API?” Excellent question! That’s next.

Now that we have our request and receive actions setup, lets combine them in the fetchWeather action, which if you recall, is what is getting called from the WeatherDatePicker onChange event:

export function fetchWeather(weatherDate, currentLat, currentLong) {

 let request_url = "https://crossorigin.me/https://api.darksky.net/forecast/8266ff95ef9bbfccf0ea24c325818f31/"

 let weather_str = weatherDate.format("YYYY-MM-DD") + "T00:00:00"

 request_url = request_url + currentLat + "," + currentLong + "," + weather_str

 return function (dispatch) {

 dispatch(reqWeather(weatherDate))

 return fetch(request_url)

 .then(response => response.json())

 .catch(error => {

 console.log("unable to get weather " + error)

 })

 .then(respData => {

 dispatch(recvWeather(weatherDate, respData))

 })

 .catch(error => {

 console.log("unable to parse weather result " + error)

 })

 }

}

Stepping through this piece by piece – first we are constructing the URL for the DarkSky request. As explained in the Redux article, this is where the thunk middleware comes into play; this is what allows the fetchWeather action to return a function instead of an object.

The first thing the returned function from fetchWeather does is dispatch the reqWeather action to update the UI showing that we are requesting the weather. It then fetches the response from the DarkSky API, dispatching the recvWeather action if it receives a valid result.

Now, we have all the plumbing hooked up to retrieve the weather based on the date chosen in the date picker. Give it a try and download the code. If you want to make updates and deploy your own Heroku app make sure to link the create-react-app buildpack in Settings.

Some next steps to try:

  • Allow the user to get customized forecasts for each campground by modifying the CampListItem component to fetch the weather, as opposed to retrieving a general area forecast as we did in this post.
  • When querying the DarkSky API instead of just getting a daily forecast, look for a week before and a week after and get an average, high, and low temp to give a better idea of seasonal weather patterns
,

Handling Events in React 101

In this article, we will be looking at how to handle events in React. Specifically, we’ll look at how to listen for some of the most common event types. We’ll also look at some of the event properties which you can work with in order to listen for two or more events at the same time. Lastly, we’re going to look at some of the event handling ‘gotchas’ in React.

How to Listen to Events

Not unlike libraries such as jQuery, React has its own event handling system which is called Synthetic Events. Synthetic Events is a cross-browser wrapper of the browser’s native event. It works the same way as the event system that you find on browsers, the only difference is that the same code will work across all browsers.

Click

Here’s an example of how to listen for a click event:

import React, { Component } from 'react';

class ShowAlert extends Component {
  
  showAlert() {
    alert("Im an alert");
  }

  render() {
    return (
      
    );
  }
}

export default ShowAlert;

The onClick attribute is added to the target element in order to specify the function to be executed when that element is clicked. Note that this isn’t limited to just buttons, you can add the onClick attribute on any element or custom component that you create. In the example above, the showAlert() function is executed once the button is clicked. onClick is a type of mouse event.

Change

Now let’s take a look at the onChange event. This is commonly used for text fields to listen for when the user types something in it. Here’s an example of how to update the contents of an element based on the current value of a text field:

import React, { Component } from 'react';

class ChangeInput extends Component {
  
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    };
  }

  changeText(event) {
    this.setState({
        name: event.target.value
    });
  }

  render() {
    return (

{ this.state.name }
); } } export default ChangeInput;

Here we’re adding the onChange attribute to the element which we want to listen for changes in contents. Note that unlike the onClick attribute, you can’t just add this to any element. You can only add it to the input of type text, textarea and select. The current value of the target element is stored in the target.value property of the event object. The event object gets passed as an argument to the function that you passed in to the onChange attribute. In order to update the contents of the h3 element, we update the component’s state with the current value of the text field.

You can find out more about handling events in forms by reading the documentation on Forms in React.

Hover

Next is the hover event. In the example below, the box will change its background color depending on whether its currently being hovered over or not. Just like the previous example, this uses state to update the styles of the box. But instead of one attribute, you need to add two: onMouseEnter and onMouseLeave. Both are pretty self-explanatory, all you have to do is assign the function that changes the default color to the onMouseEnter attribute. And then the function for bringing back the default color to the onMouseLeave attribute.

See the Pen AppendTo: React Events 101 – Hover by Wern Ancheta (@wernancheta) on CodePen.

Here are the codes:

import React, { Component } from 'react';

var styles = {
  box: {
    width: '100px',
    height: '100px'
  },
  in: {
    backgroundColor: 'red'
  },
  out: {
    backgroundColor: 'green'
  }
};

class HoverBox extends Component {
  
  constructor(props) {
    super(props);
    this.state = {
      box_state: 'out'
    };
  }

  changeColor() {
    this.setState({
        box_state: 'in'
    });
  }

  resetColor() {
    this.setState({
      box_state: 'out'
    });
  }

  render() {
    return (
); } } export default HoverBox;

Event Properties

We already know that an event object gets passed to the function that takes care of handling the event. As we’ve seen earlier, there’s the target property which allows us to get the actual element being targetted by the event. If its a text field, the current value can be found on the value property of the target.

Depending on the type of event, there are different properties that you can access in order to further customize how events will be handled. For example, the onClick event is a type of Mouse Event. But we can also use it in combination with other events. One common example of this is the pressing of the Ctrl key on the keyboard while clicking on the files you want to select.

select files

Here’s a React component that simulates that behavior:

See the Pen AppendTo: React Events 101 – Select Boxes by Wern Ancheta (@wernancheta) on CodePen.

Here are the codes:

import React, { Component } from 'react';

var styles = {
  box_container: {
    padding: '20px'
  },
  box: {
    width: '50px',
    height: '50px',
    float: 'left',
    marginLeft: '10px'
  },
  default_box: {
    backgroundColor: 'gray',
  },
  selected_box: {
    backgroundColor: 'orange'
  }
}

class SelectBoxes extends Component {
  
  constructor(props) {
    super(props);
    this.state = {
      boxes: [
        false,
        false,
        false
      ]
    }
  }

  selectBox(index, event) {
    var box_states = this.state.boxes;
    if(!event.ctrlKey){
      box_states = [
        false,
        false,
        false
      ];
    }

    var is_selected = box_states[index];
    box_states[index] = !is_selected;
    this.setState({
      boxes: box_states
    });
  }

  renderBoxes() {
    return this.state.boxes.map((is_selected, index) => {
      let box_type = 'default_box';
      if(is_selected){
        box_type = 'selected_box';
      }
      return (
); }); } render() { return (

{ this.renderBoxes.call(this) }

); } } export default SelectBoxes;

In the constructor, we’ve initialized the state with an array containing the select state for each of the boxes. These boxes represent the files. The renderBoxes() method renders the boxes and styles them according to their select state. If a box is clicked without simultaneously pressing the Ctrl key, it resets the state to its default one (everything is deselected) because ctrlKey property would have false as its value. Below that, we simply toggle the select state of the box being clicked on.

Another example is keyboard events such as onKeyUp, onKeyDown and onKeyPress. When used, each of these events have properties pertaining to the actual key that you pressed:

  • altKey – a boolean value indicating whether the alt key is pressed along with another key.
  • charCode – the code of the key being pressed.
  • ctrlKey – a boolean value indicating whether the Ctrl key is pressed along with another key.
  • key – the actual key that was pressed.
  • shiftKey – a boolean value indicating whether the shift key is pressed along with another key.
  • which – pretty much the same as the charCode.

There are many other properties which you can use based on the event type, so be sure to check out the list of supported events in React.

React Event Handling Gotchas

Lastly, let’s take a look at some of the most common gotchas when it comes to event handling:

  • this can have different meaning.
  • You can’t listen to events directly from your custom components.
  • Not all DOM events have SyntheticEvent equivalents.

this can have different meaning

this can have a different meaning depending on how you attached the event handling function. For example, in the ShowAlert component earlier. We just specified the function directly without binding it to the component context:


This is because we didn’t really need to access anything in the component context (e.g. the state). But if you need to be able to access the state and manipulate it, you have to use bind to bind the component context to the function. This way you can use this inside the function to refer to the component itself:


Note that this is only true if you’re using ES6 classes to declare your components. If you’re using React.createClass, this will always refer to the component without the need to use bind.

You can’t listen to events directly from your custom components

If you have a custom component named Box, you can’t do something like this:

import Box from './components/Box';

class App extends Component {

  danceBox() {
    //make the box dance
  }

  render() {
    return 
  }
}

See what we did there? We added the onClick event handler directly to the Box component. But this wouldn’t really work because this only means we’re passing in an onClick props to the Box component. To actually attach the click event handler, you need to add onClick to the actual component. It’s not really a good practice to use reserved words for props so you need to change the name as well:

Then on the Box component, use the clickHandler props:

Not all DOM events have SyntheticEvent equivalents

If you compare the DOM events listed on MDN with the Synthetic events in React, you’ll see that not all of the DOM events has an equivalent synthetic event. For example, there’s no synthetic event for listening for when the browser window is resized. In such cases, we need to fallback to DOM events to do the work for us. All you have to do is to attach the event listener using window.addEventListener. This accepts the event you want to listen to as its first argument, and the function that will handle the event as the second argument. The attaching of the event listener is done when the component has been mounted (componentDidMount). Don’t forget to remove it when the component is unmounted (componentWillUnmount). The handleResizedScreen function handles the event by getting the current width and height of the window, then updating the state so that the displayed width and height also changes.

import React, { Component } from 'react';
import '../App.css';

class ResizeWindow extends Component {

  constructor(props) {
    super(props);
    this.state = {
        width: window.innerWidth,
        height: window.innerHeight
    };
  }

  handleResizedScreen() {
    this.setState({
        width: window.innerWidth,
        height: window.innerHeight
    });
  }

  componentDidMount() {
    window.addEventListener("resize", this.handleResizedScreen.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.handleResizedScreen.bind(this));
  }

  render() {
    return (

 

{ this.state.width } x { this.state.height }
); } } export default ResizeWindow;

Here are the contents of the App.css file:

.centered {
  position: fixed; 
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 30px;
}

Conclusion

That’s it! In this tutorial you’ve learned all about events in React. With this knowledge, you’ll now be able to create React apps that makes full use of events. You can find all the codes used in this tutorial in this Github repo. For more information regarding events in React, check out the official documentation on Events.

, , ,

Google Maps in React / Redux: Interactivity Across Different Components

Rich UIs provide users with a variety of ways to interact. For example, HipCamp, a platform for discovering camping opportunities, uses a combination of a map-based UI and an informative list of campgrounds:

hipcamp.png

This split UI gives users an idea of location through identifying the campground on a map, while keeping the map tidy by using the marker info windows as basic identifier, keeping the more verbose content within the campground list.

Explore React Courses

In this post we will build on our previous learnings in list filtering through state management in React/Redux by adding a map to the UI. We will see how to use state to link the list and map views together, enabling the user to leverage the information of both UI elements when interacting with one or the other. We will also extend the filtering functionality to the markers by connecting the map components to the same state elements as the filter components. The resulting app will filter both the markers and the campground list, and provide users with visual cues when interacting with one or the other. Clicking on a marker will pop up an info window showing the campground name and also highlight the corresponding list item by changing the border. Likewise, clicking a list item will open the info window for the corresponding marker and change the item border:

map.png

You can get the code for this app on GitHub and interact with it live at this Heroku demo app. We will continue using the google-maps-react npm module and some of the techniques outlined on Full Stack React for working with this package. All of our state management will be done via Redux, as opposed to at the component level in the Full Stack React article.

Adding the Map

Picking up where we left off in the previous post, we will add a google maps container to CampFilterApp.jsx:

render() {

 return (

 <div className="container">

 <Jumbotron>

 <h1>
 Crater Lake Camping
 </h1>

 </Jumbotron>

 <br></br>

 <CampFilterList {...this.props }/>

 <br></br>

 <CampMapContainer {...this.props }/>

 <br></br>

 <CampList {...this.props }/>

 </div>

 )
};

The CampMapContainer component will serve as a wrapper for the google maps components, and a point of entry for the GoogleApiComponent provided by google-maps-react. First lets look at the render method for CampMapContainer.jsx:

 

render() {

 return (

 <div>

 <CampMap google={this.props.google}>

 {this.props.markers.map(marker =>

 <Marker

 key={marker.get('title') }

 title={marker.get('title') }

 description={marker.get('description') }

 properties={marker.get('properties') }

 position={marker.get('position') }

 mapOn={marker.get('mapOn') }

 addMarker={this.props.addMarker}

 onMarkerClick={this.props.onMarkerClick}/>

 ) }

 <InfoWindow {...this.props}

 marker={this.props.activeMarker}

 visible={this.props.showingInfoWindow}>

 <div>

 <h4>{this.props.selectedTitle}</h4>

 </div>

 </InfoWindow>

 <CampList {...this.props}/>

</div>

 ) }

We have four components inside the container – CampMap is a container for the map itself, which contains a marker component for each marker in our markers property and an InfoWindow component to be set based on the activeMarker property. We will discuss these components more in detail in a bit.

After the class definition in CampMapContainer.jsx, we will add an export for the google maps component:

let key = config.getGoogleKey()

export default GoogleApiComponent({

apiKey: key

})(CampMapContainer)

You can use the API key included in the config supplied with the config.js file for demonstration purposes, but please don’t abuse it! You can use the google-maps-react package without an API key, but by providing one we receive a google property which can be passed to the components to create markers, info windows, and maps as we will see shortly. Notice that the <CampMap> component in the render method above makes use of the google property.

Lets dive into the Google Maps components.

The CampMap Component

This component sets up our map and renders the Marker components. In the render method, we set the min size for the map and call the renderChildren function. You can check out that code in CampMap.jsx. Essentially, it will render any children of the map object, in our case the Marker components, passing on the google and map properties.

render() {

 const style = {

 minWidth: '400px',

 minHeight: '400px'

 }

 return (

 <div className="row">

 <div style={style} ref='map'>

 {this.renderChildren() }

 Loading map...

 </div>

 </div>

 )

}

Recall above that we passed the google property to this component. The API connection is asynchronous, meaning that initially this property will be undefined. When the API returns, the google property will be updated, resulting in a ComponentDidUpdate event on the CampMap component. This has two impacts:

  1. When the render method is initially called, and the Markers are rendered as a result, the map property passed to the Markers in renderChildren will be undefined. This means the markers will not be attached to the map since it does not yet exist. In order to attach the markers to the map we will need to renderChildren again after the API returns.
  2. We need to wait until the API returns a valid google property to load the map.

To account for this, we will handle the ComponentDidUpdate event in the CampMap component, calling both the loadMap function that draws the google map and forceUpdate, which will force the component to re-render including the call to renderChildren. We will only do this if the google property has been updated, to avoid re-rendering for other cases where componentDidUpdate is fired. The loadMap function sets the map parameters and attaches it to the DOM, see CampMap.jsx.

componentDidUpdate(prevProps, prevState) {

 if (prevProps.google !== this.props.google) {

 this.loadMap();

 this.forceUpdate()

 }

}

The Marker Component

Now that we have our map created, let’s take a look at the Marker component, which receives the google and map properties from its parent component, CampMap, in addition to these properties defined in CampMapContainer:

<Marker

key={marker.get('title')}

title={marker.get('title')}

description={marker.get('description')}

properties={marker.get('properties')}

position={marker.get('position')}

mapOn={marker.get('mapOn')}

addMarker={this.props.addMarker}

onMarkerClick={this.props.onMarkerClick}/>

Because google maps renders components directly to the DOM, the render method of this component simply returns null. Instead, we render the marker when there is a change in the map property or in the marker properties or mapOn properties. We are only looking at changes in these specific marker properties because the others are static in our application. See the ComponentDidUpdate method in Marker.jsx

You’ll notice that we are passing two actions down to the Marker component; addMarker and onMarkerClick. The addMarker action is used to create a list of google marker objects as part of the Redux state. This marker array will be used to allow interactivity between the markers and the campground list items. The onMarkerClick action will be used to set the info window content. We will discuss these actions more in detail later on. The InfoWindow component implementation is from the Full Stack React Google Maps article, which you can reference to understand the lifecycle of this component.

The CampListItem Component

We need to make a few changes to our CampListItem component from the last post to change the border of the selected element and enable opening the corresponding marker’s info window. Let’s take a look at the image in the CampListItem component render method:

<img src={img_url} alt="campground" ref="cg_image" style={{width:200, height:100}} onClick={() =>this.props.onMarkerClick(this.getMarker(this.props.title))}></img>

We’ve added a ref property to the image which we will use to set the border style when the item is selected. We’ve also added a click handler to call onMarkerClick with the current marker. This is the same onMarkerClick called by the Marker component, which will set the info window content and open/close it as required. Notice that we are calling a local function getMarker to retrieve the current marker for the onMarkerClick parameter. First let’s take a look at setting the style with the ref property in CampListItem.jsx:

componentDidUpdate(prevProps, prevState) {

if (this.props.activeMarker !== prevProps.activeMarker) {

let img_ref = this.refs.cg_image

if (this.props.showingInfoWindow && (this.props.selectedTitle === this.props.title)) {

img_ref.style.border = "3px solid black"

}

else {

img_ref.style.border = null

}

}

}

On ComponentDidUpdate we check to see if the activeMarker field has changed, and if so we proceed with changing the image border. Next, we will either add the border if this item is selected, or remove it if it is no longer selected. If it turns out that the info window should be shown and the selectedTitle property matches the title of the current marker we will update the border to “3px solid black”, otherwise we set the border to null.

Recall that we have been using addMarker to create an array of google maps markers as part of our Redux state whenever a new marker is rendered. We now have two arrays of markers as part of our state, from index.js:

function set_state(campgrounds) {

 store.dispatch({

 type: 'SET_STATE',

 state: {

...

 markers: campgrounds,

 gmapMarkers: [],

 ...

}

})

}

The markers array is our geoJSON-based markers used for filtering and displaying data. The gmapMarkers array is for the google marker objects we need for the map markers. Both sets of markers have a title field that can be used to link the two. In the CampListItem component, the marker property is from the markers array. The onMarkerClick action needs a marker from the gmapMarkers array in order to attach the info window to the correct marker, so we have a helper function getMarker that retreives the matching gmapMarkers element to provide to onMarkerClick:

getMarker(title_match) {

 let match_list = this.props.gmapMarkers.filter(item =>

 item.get('title') === title_match

 )

 if (match_list) {

 return match_list.first()

 }

 else {

 return null;

 }

}

Where this.props.title is provided as the title_match parameter.

Now that we’ve discussed the component hierarchies, let’s take a look at how to hook up these actions in Redux.

Redux Implementation

Remember we first need to add our new actions to the action_creators.js file, which you can review here. Next, we add the following to our reducer.js file to handle these new actions:

function onMarkerClick(state, marker) {

 return state.merge(Map({

 'activeMarker': marker,

 'selectedTitle': marker.get('title'),

 'showingInfoWindow': true

 }))

}

function addMarker(state, marker) {

 let markers = state.get('gmapMarkers')

 let newMarkers = markers.push(marker)

 return state.update('gmapMarkers', oldmarkers => newMarkers)

}

Whenever the markerOnClick event is fired, we want to show the info window, so showInfoWindow is set to true. activemarker and selectedTitle are set based on the marker passed up from a CampListItem or Marker component. For addMarker, we simply add the new marker to the existing gmapMarkers array. Don’t forget to add the new actions to the reducer:

export default function (state = Map(), action) {

 switch (action.type) {

 case 'SET_STATE':

 return setState(state, action.state);

 case 'CHANGE_FILTER':

 return changeFilter(state, action.filter);

 case 'MARKER_CLICK':

 return onMarkerClick(state, action.marker)

 case 'ADD_MARKER':

 return addMarker(state, action.marker)

 default:

 return state

 }

}

One last change to make in the reducer, and this is for the changeFilter action. Recall that we used a mapOn property in the Marker component:

if (!this.props.mapOn) {

 this.marker.setMap(null);

}

else {

 this.marker.setMap(map)

}

The mapOn property was added to the geoJSON-based markers array to set marker visibility based on the filter settings. Adding the following to changeFilter in reducer.js will set mapOn to true of the marker should be shown:

let markers = state.get('markers')

let updatedMarkers = markers

markers.forEach(marker => {

 let markerIndex = getMarkerIndex(state, marker.get('title'))

 let mapOn = true

 active_filters.forEach(item => {

 if (marker.get('properties').get(item.get('id')) !== true) {

 mapOn = false

 }

 })

Based on the mapOn property we can “remove” the markers not to be displayed based on the current filter settings by marker.setMap(null) if mapOn is false.

And that’s a wrap! Using the gmapMarkers property and invoking the onMarkerClick action from both the Marker and CampListItem components we have enabled opening of the InfoWindow from clicking on the CampListItem image and highlighting the CampListItem image as a result of clicking on the Marker. The additional field mapOn enables us to filter both the campground list and the markers.

,

3 Libraries and 3 Ways to Handle AJAX in React Apps

For React beginners coming from a jQuery background, one of the first few questions that come up is how to perform AJAX requests within a React app. The quick answer to this is you can’t, because React is only a view library. It doesn’t come with the functionality to make AJAX or network requests. But the good news is there are libraries which you can use to add this ability to your apps.
In this article we’re going to look at some of the methods which you can use to make AJAX calls within your React app. As some of you might already know, you can actually use React on the server and on mobile apps. That said, we will only be focusing on React on the browser. The article is divided into two sections. In the first section, we’re going to look at some of the libraries which you can use to easily perform AJAX requests and on the second section, we’re going to look at how you can use those libraries inside your React app.

Libraries to Use

Before diving into using libraries for AJAX requests, it’s important to know that there are two ways in which you can make AJAX requests by using what’s available in the browser: XMLHttpRequest and the Fetch API. If you want to keep your React app as lean as possible, you can use either of those two to perform AJAX requests. Just be sure to check Caniuse.com for browser support.
Here are the list of libraries and sample code on how to use them:

axios

Axios is a promise based HTTP client for the browser and Node.js.

npm install axios
var request = require('axios');
axios.get('https://localhost:3000/data.json')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Superagent

Superagent is small progressive client-side HTTP request library.

npm install superagent
var request = require('superagent');
request
  .get('https://localhost:3000/data.json')
  .end(function(err, res){
    console.log(res);
  });

Request

Request is a simplified HTTP request client.

npm install request
var request = require('request');
request('https://localhost:3000/data.json', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(response);
  }
})

Fetch

Here is a polyfill for the Fetch API. This allows support for more browsers.

npm install whatwg-fetch
var fetch = require('whatwg-fetch');
fetch('https://localhost:3000/data.json')
  .then(function(response) {
    return response.json();
  }).then(function(json) {
    console.log(json);
  }).catch(function(err) {
    console.log(err);
  });

Using AJAX in your React App

Now let’s take a look at the methods on how we can actually use those libraries inside a React app. We can make AJAX calls in the following places:

  • Root Component
  • Containers
  • Redux Middleware

Root Component

If your app is fairly light and simple, you can make your AJAX calls within the root component and pass in the response to the relevant components through props. For this to work you need to use state in your root component so that you can update the relevant component when a response comes back. Here’s an example:

import React, { Component } from 'react';
import List from './components/List';
import axios from 'axios';
class App extends Component {
  constructor(){
    super();
    this.state = {
      names: []
    };
  }
  render() {
    return (

); } componentWillMount() { var self = this; axios.get(‘https://localhost:3000/data.json’) .then(function (response) { self.setState({ names: response.data.names }); }) .catch(function (error) { console.log(error); }); } } export default App;
Here’s the code for the List component:

import React, { Component } from 'react';
class List extends Component {
  constructor(props){
    super(props);
  }
  render() {
    return
    {this.props.names.map(this.renderItem)}

; } renderItem(name) { return

  • {name}

; } } export default List;

Containers

If you are using Redux or just a plain React app, you can add your AJAX calls inside containers. The main idea for this approach is to create containers for components that needs to fetch their data via AJAX. This way you’re not violating the Single Responsibility Principle that components should be only used for presentation.
If you’re not aware of it yet, there’s this idea of Presentational and Container components in React. Basically, the idea is that presentational components are concerned with how things look. While container components are concerned with how things work. Here’s an example:

import React, { Component } from 'react';
import ListContainer from './containers/ListContainer';
class App extends Component {
  render() {
    return (

); } } export default App;
Below is the code for the ListContainer. The same code is used for the List component which we’ve seen in the last section. This example uses whatwg-fetch instead of axios.

import React, { Component } from 'react';
import List from '../components/List';
import 'whatwg-fetch';
class ListContainer extends Component {
  constructor(props, context) {
    super();
    this.state = {
        names: []
    };
  }
  componentWillMount() {
    var self = this;
    fetch('https://localhost:3000/data.json')
      .then(function(response) {
          if (response.status >= 200 && response.status < 300) {
            return response.text();
          } else {
            var error = new Error(response.statusText)
            error.response = response
            throw error
          }
      })
      .then(function(body) {
        self.setState({
          names: JSON.parse(body).names
        });
      });
  }
  render() {
    return ;
  }
}
export default ListContainer;

Redux Middleware

Lastly, for medium to large-sized Redux apps, you can put your AJAX calls inside middlewares.
First you need to create the middleware (services/data-service.js). This is where you perform the AJAX request when the GET_NAMES action is executed. If the request fails, dispatch another action named GET_NAMES_FAIL and if it succeeds in getting the data, dispatch the GET_NAMES_OK action. Later on we’ll look at the reducer which will handle these actions. For now, just remember that middlewares are reponsible for dispatching atleast two actions: one for failed request and one for successful request.

import request from 'superagent';
const dataService = store => next => action => {
    next(action);
    switch (action.type) {
        case 'GET_NAMES':
            request
                .get('https://localhost:3000/data.json')
                .end((err, res) => {
                    if (err) {
                        return next({
                            type: 'GET_NAMES_FAIL',
                            err
                        });
                    }
                    const names = JSON.parse(res.text).names;
                    next({
                        type: 'GET_NAMES_OK',
                        names
                    });
                });
            break;
        default:
            break;
    }
};
export default dataService;

The status reducer (reducers/status.js) gets called for each of the actions in the app. The idea here is to return only true once there’s already the data, otherwise return false. Or return the current state if any other action is received:

const status = (state = false, action) => {
    switch (action.type) {
        case 'GET_NAMES':
            return true;
        case 'GET_NAMES_OK':
            return false;
        case 'GET_NAMES_FAIL':
            return false;
        default:
            return state;
    }
}
export default status;

The list reducer (reducers/names.js) is the one which receives the payload data once it becomes available. We already know that the GET_NAMES_OK action is fired when that happens, so we check for that here and simply return the actual data.

export default function listReducer (state = [], action) {
    if (action.type === 'GET_NAMES_OK') {
        return action.names;
    }
    return state;
}

Next, we need to combine those reducers so they’re under the same object with status and names as their properties:

import {
    combineReducers
} from 'redux';
import names from './names';
import status from './status';
const nameList = combineReducers({
    status,
    names
});
export default nameList;

Create the ListContainer (containers/ListContainer.js) which will utilize the array of names. This component subscribes for changes in the store, so that by the time the names array becomes available, it can just update its state. The List component which ultimately displays the data is updated via the names props (note: the code is the same as the List component (components/List.js) that we used in the previous section).

import React, { Component } from 'react';
import List from './List';
class ListContainer extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      names: []
    };
  }
  componentWillMount() {
    this.context.store.subscribe(() => {
        let state = this.context.store.getState();
        this.setState({
          names: state.names
        });
    });
  }
  render() {
    return ;
  }
}
ListContainer.contextTypes = { store: React.PropTypes.object };
export default ListContainer;

Use the ListContainer in your main App (App.js) component

import React, { Component } from 'react';
import ListContainer from './components/ListContainer';
class App extends Component {
  render() {
    return (

); } } export default App;
Finally, bring everything together in your root component (index.js) by creating a store that uses the reducers and the middleware that you created earlier. On the last line, dispatch the GET_NAMES action in order to trigger the execution of the GET_NAMES action in the dataService middleware.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import reducer from './reducers/index';
import dataService from './services/data-service';
let store = createStore(reducer, {}, compose(applyMiddleware(dataService)));
ReactDOM.render(
  (
  ),
  document.getElementById('root')
);
store.dispatch({type: 'GET_NAMES'});

Other Methods

The methods mentioned above are just a sample of many ways you can use AJAX within your React app. If you want to learn about the other approaches, read on the following links:

Conclusion

That’s it! In this tutorial you learned about the libraries and ways in which you can make AJAX requests inside your React app. You can check out the codes used in this tutorial on this Github repo

, ,

Introduction to Data Binding with MobX

Once you get past very simple applications, programming on the web can become a nightmare of event handling and notifications, where the state of an application is spread out among dozens of different text boxes, select boxes and similar components. This is one reason why Model/View/Controller architectures (MVC) have become pretty much de rigour (along with multiple variations on this theme) in web programming.

However, MVC also requires that when you change the model, the view will change in response. This is pretty easy to accomplish when there is a direct one-to-one relationship between a component and its associated value. Where things begin to fall apart is when multiple components are dependent upon the same set of values, or when changes in values change other values that have component dependencies. This is a behavior you see quite often with spreadsheets (and one reason why translating spreadsheets into web applications can be quite a headache).

Mobx and MVC

The Mobx library makes use of ES2015 and (with later version) ES2017 decorators in order to identify specific variables or objects and make them “observable”. What this means in practice is that the framework “keeps track” of these variables, and any time the variables change, then the a notifier is activated for handling the impacts of these changes.

An example of this can be seen in the following CodePen.

See the Pen MobX+React test by Kurt Cagle (@kurt_cagle) on CodePen.

This example is deliberately kept simple to illustrate the process. Here, you can change a person’s first or last name, or change their age by using a numeric input control. This data is kept within a particular data structure, when either part of the name is changed, a new variable called flippedName is calculated, which holds an alternative medium state (in this case the name given as “lastName, firstName”). Finally, if the age of the person is 18 or higher, the flipped name appears green – the person involved can participate in whatever activity is being supported. If the age is under 17, however, the flipped name turns red, and a warning message is posted.

This example is especially useful because the data is entangled – the dispay of the output text is dependent upon both the names and the age. Moreover, the input fields make it possible to update the model, showing a “round trip” type activity that is common with MVC type applications.

Dipping into the code, the first few lines take advantage of the Babel transpiler to implement the ES2017 decorator capabilities. Decorators are pre-process directives that perform “meta-operations” on code, and are in effect the equivalent of “aspect” programming used in languages like Java. These can be used to automate logging, to set up services from functions and, in the case of mobx, to identify and manage variables and objects to be watched.

Explore React Courses

The @observable decorator is syntactic sugar for the older ES2015 implementation mobx.observable(...). This is not a function in the traditional sense. Instead, observers act on functions and expressions of code prior to them actually being evaluated, deferring the actual evaluation until some context structures can be set up.

class Person {

@observable firstName;

@observable lastName;

@observable age:number;

constructor(_firstName,_lastName,_age){

this.firstName = _firstName;

this.lastName = _lastName;

this.age = _age;

this.bind("firstName");

this.bind("lastName");

this.bind("age");

}

@computed get flippedName() {return `${this.lastName}, ${this.firstName}` }

In this case, three properties of a given class are identified as being observable – firstName, lastName and age. This means that, when an instance of this is created, then the instance members will be observable.

The bind() function in this class is not directly mobx related. Instead, it establishes a simple binding between an input element with an id that has the same name as the variable in question. That way, if you change an input field, you also change the model, and by extension change any functionality that depends upon the variable being changed.

bind(prop,defaultValue){

document.querySelector(`#${prop}`).value = defaultValue!=null?defaultValue:this[prop];

document.querySelector(`#${prop}`).addEventListener("input", (evt)=>{this[prop] = evt.target.value});

}

An area where mobx really comes in handy is for those scenarios where you want to make computed properties. A computed property is one that has a dependency upon observable properties – when you change the observable, you also change the computed value. Here, the first and last names are inverted to create a “lastname, firstname” type string in this read-only getter. By using the @computed decorator, should the independent variables (firstName or lastName here) change, then the @computed getter is re-evaluated.

This is by itself actually a huge benefit that mobx provides. While for something like inverting name takes comparatively few cycles to perform, when you have complex structures, regular expressions, template strings, asynchronous calls or similar processes, not having to rerun a getter when nothing has changed can result in huge cycle and memory savings. The @computed decorator feature right here is well worth the price of admission to Mobx.

The mobx.autorun() decorator is one of the few that doesn’t have an associated @ property. It is one of the big workhorses of Mobx, however. Whenever an observable or computed property is changed mobx.autorun is called IF the enclosed expressions have dependencies upon those variables.

In the sample codepen, I define three “render” methods. The first displays the flipped label. The second changes the color of the inverted title from green to red if the age given is below 18, while the final method adds a warning beneath the input fields indicating when a person is too young to participate in the program.

There are three such mobx.autorun() statements, one that calls each of these functions respectively. When a user changes the first name using the input, the showLabel() and warn() functions are invoked. If they change the age, the redLabel() and warn() functions are invoked. Finally, if the last name is changed, then only showLabel() gets invoked. Why? The showLabel() function has a dependency on the first and last name, while warn() uses only the first name, and redLabel() has no dependency at all upon the last name.

The advantage of this should be obvious, especially with complex forms or applications. If a component is unchanged, then it should not be necessary to re-render it, especially when there are a lot of interdepencies acting upon that component.

In that respect, the relationship between MobX and React should be obvious. MobX creates a way to indicate when the broader (global) data model changes, notifying downstream functions when independent variables and automatically computing @computed values that can then reduce the overall computational cost. React maintains a data model at the component level, so that when state variables or attributes change, only those portions of the component dependent upon those changes gets updated.

This article focused on the basic functionality of mobx. A subsequent article will focus will look at how you can use mobx and react together to keep the total amount of unnecessary work for your application to a minimum.

Explore React Courses

, , , ,

230 Curated Resources and Tools for Building Apps with React.js

This post will curate the best resources, tools, libraries, and articles that will help you learn to build production applications with React.js. This 6000 word post will take you from getting started with React, through UI design, routing, testing, deployment, and continuous integration. There are many sections and you should feel free to jump to the resources you need.
Getting Started
+ Demos and Apps
+ Tutorials and Articles
+ Video Tutorials and Courses
+ Community
+ Boilerplates
+ UI Components
+ UI Libraries and Frameworks
+ Routing
+ State Management
+ Other Useful Libraries
Development Tools
+ Text Editors
+ Build Tools
Testing
+ Articles
+ Utilities
+ Automated Backend Testing Services
Performance
+ Articles
+ Tools
+ Libraries
Deployment
+ Continuous Integration Articles
+ Continuous Integration and Deployment Software
+ Cloud Server Provider
+ Continuous Integration in React Apps
Resources for Further Learning
+ Articles and Tutorials
+ Courses
+ Books
+ Talks and Conferences
+ More React Resources

Explore appendTo’s React Courses

Getting Started

First off, let’s start at the very beginning. This section assumes you have zero-knowledge on React and have at least a solid foundation on JavaScript basics.

Demos and Apps

You already know that you want to learn React (that’s why you’re here right?). But a good first step when learning about a new technology is to know what’s possible with it. And the best way to go about that is to check out demos and existing apps that have been built with it.

Demo Apps

Production Apps

Tutorials and Articles

Now that you know what’s possible with React, it’s now time to take a look at how you can get started learning it.

If you’re the type of person who wants to have a general idea on how a specific technology works, then ReactJS for Stupid People is a good place to start. It talks about what React is, what you can do with it, its limitations, and whether you should use it for your future projects or not.

If you’re like most people, you either came from a jQuery or Angular background before you came to know about React. Tutorials which uses a well-known library as a point of reference in learning something new is a good way to understand how things are done in that new technology. Being able to translate what you’re used to doing in an older technology to and apply it to a new one can be very empowering to new developers who are just trying the waters.

Now that you have an idea on how React works, it’s now time to dive into the core React concepts. Taking the time to understand the core concepts first before trying to write even a single line of code can really go a long way when learning React, and in fact (news flash coming up) any other new technology that you’re trying to learn. This will make the code that you see in React tutorials “click” faster. It also ensures that you won’t just end up copy-pasting the code from these tutorials. Having a good understanding of the core concepts enables you to distinguish how a specific thing works when you see them in action. So without further delay, here are a few tutorials you can read in order to understand the core concepts behind React:

Video Tutorials and Courses

Free Courses

  • Egghead.io: React Fundamentals – this series will explore the basic fundamentals of React to get you started.
  • Mindspace: ReactJS Basics – teaches the basic concepts of React.
  • Learn ReactJS – if you want a more hands-on React course, this one is for you. Aside from the usual “getting to know the syntax” part, they also have projects and quizzes to make sure you really understand what you learned.
  • ReactJS Program: React.js Fundamentals – uses a combination of tutorials, video tutorials and a project that you will build throughout the whole course.

Paid Courses

If you have some cash to spare, consider enrolling on the following courses:

  • Powering Up with React – a combination of video tutorials and hands-on exercises to get your hands dirty in using React.
  • React for Beginners – a course by Wes Bos, a Full Stack Developer, Speaker and Teacher from Canada. The course is a bit pricey but it will be worth it, because this course covers all there is to know about the fundamentals of React.js. Each video tutorial is really concise, very engaging and most important of all, it’s not sleep-inducing.
  • React.js: Getting Started – learn the basics of React.js, and build an in-browser, math skills kids’ game from scratch with it.

Community

Now that you’ve begun your journey in writing React code, and maybe have followed through a tutorial or two.

In your journey in learning React, there will always be a time wherein you get stuck with a specific bug or error in your code. Often times simply searching for that specific error on Google would help. But what if there’s no error at all? Or Google doesn’t really return useful results. In those cases what you need is a community. Most of us already know Stackoverflow. Most of the search results that you see on Google when you search for a specific error are almost always from Stackoverflow. But aside from Stackoverflow there are other good places where you can get help and talk about React stuff in general.

Now that you have an idea how React works, its core concepts and how to build things with it, its now time to take things further by learning about the tools which you can use while developing apps with React.

Boilerplates

A boilerplate is a useful tool for quickly getting started with a React project. As you might have already found out using the resources given above, the React code (JSX) that you write can’t actually be executed by the browser. This means that it has to go through a compilation process before the browser can understand it. The compiler accepts your JSX code and spits out the plain JavaScript code that’s readable by the browser. This is where boilerplates comes in. One of the tools which comes with a boilerplate is the build tool, which is responsible for compiling your JSX code.

To put it simply, boilerplates comes with a collection of tools and libraries that are commonly needed in developing React apps. Examples of such tools are build tools, test runners, and libraries for routing and state management.

  • Create React App – if you want to quickly get started writing React apps without worrying too much about the build/compile process, this is the way to go. In my own opinion, this is the only beginner-friendly boilerplate among this list.
  • React Starter Kit – if you’re looking for a boilerplate that allows you to easily set up not just the front-end but the back-end as well, this boilerplate is for you. It is built on top of Node.js, Express, GraphQL, React.js, Babel 6, PostCSS, Webpack, and Browsersync.
  • React Boilerplate – a production-ready boilerplate for starting out React projects. Highly focused on performance and best practices.
  • React-Redux Starter Kit – if you want a boilerplate which has minimal features and isn’t too opinionated about how to do certain things (project structure, build configuration) then this one is for you.

Those are just a few of the boilerplates that allows you to get started with your React projects quickly. Note that it’s not a requirement to use these boilerplates. Sooner or later you’ll find out that they’re either too rigid or too hard to customize. This is because some boilerplates can be too opinionated about how to go about things. Once you’ve tried using one or two boilerplates, you’ll pretty much have an idea on how to build your own. Every project is different so building your own boilerplate makes sense, since you only include things as you need them. This also adds up to your productivity later on, as you no know exactly where to look when you need to customize things.

UI Components

The main idea for using React is to be able to create UI components that can be reused anywhere in your app. Since React is a pretty popular library, developers and designers around the world have already created a lot of useful components that can be used in most projects. This means that you don’t need to write everything from scratch. Most of the components that you might need in your project might have already been written before.

In this section, let’s look at some useful components which you can use in your projects.

Those are just some of the components which you can use on most projects. If you need to find a custom component, you can check out the following component curators:

If you’ve looked through the curators above, you’ll notice that each component either points out to one of these two sites:

  • Github – hosts the source code for the components.
  • NPM – package manager that enables developers to install the components locally.

This means that you can actually directly search on Github or NPM for your React components and libraries.

UI Libraries and Frameworks

If you want your apps to have a standard look and feel, a good place to start is by picking a UI library or framework. Libraries and frameworks comes with a set of components with the same theme. Each of them comes with a different set of components and a different way of doing things, so you have to choose which one fits your needs and your values.

  • Material-UI – React components that implements Google’s Material Design.
  • Ant Design – a collection of components that follows Ant Design, a design language for creating user friendly and beautiful websites.
  • React Bootstrap – the Bootstrap framework re-implemented using React.
  • Rebass – a collection of 57 Configurable React Stateless Functional UI Components.
  • React Toolbox – similar to Material-UI in that it also implements Google’s Material Design. The only difference is that it uses css modules intead of inline styles.
  • Elemental UI – a UI Toolkit for React.js Websites and Apps. If you’ve used Bootstrap before, the look and feel of their UI is similar to Bootstrap’s.
  • Grommet – an accessibility-focused framework for creating amazing user experience.
  • Belle – Configurable React Components with great UX.
  • Cx – a modern framework for building visually appealing, data-oriented, web applications.
  • Reusable Components by Khan Academy – useful components from Khan Academy.
  • VistarMedia Components – a collection of React components from VistarMedia. The components has the same look as Bootstrap.
  • React Topcoat UI – if you’ve used the Topcoat CSS framework before and you want the same look and feel for your React app.

Explore appendTo’s React Courses

Routing

Routing is an important part of every application. It keeps the UI in sync with the current URL that is being accessed by the user. For example, when http;//myapp.com/#user/1 is accessed, the UI will automatically update to show the page being asked.

Here are some of the routing libraries that you can use with React:

  • React Router – the De facto routing library for React. In the beginning, this is what you want to use as it includes all the bells and whistles that you need to start experimenting with routing.

Once you’re acquainted with React Router, you might notice that there are some features that you don’t really need, or you don’t really like the way it does things. Here are a few alternatives that you might want to check out:

  • React Mini Router – if you don’t want your routing solution to consume that much space, you can use this library instead. It has a few external dependencies and only becomes 4kb when gzipped.
  • React Router Component – a declarative router component for React.
  • Universal Router – A simple middleware-style router that can be used in both client-side (e.g. React, Vue.js) and server-side applications

  • router5 – a framework agnostic routing solution.

State Management

Another important part of any application is how you manage the state. At this point, we already know that each component can have their own state. This works for really small applications because you can just pass the state from one component to another by means of props. But for real-world apps, you need a way to make the state accessible throughout the whole app. Especially the one’s that are “global” by nature (e.g. settings). This is where state management comes in. React doesn’t come with this kind of functionality, but thankfully there are libraries that allows you to manage global app state in a sane manner.

Redux is one such library. Redux allows you to have a global state for your app so that the different components in your app can communicate with each other. Note that Redux isn’t specific to React, so you have to install React Redux as well so that you can easily work with Redux within the React environment. After learning plain React, Redux is the second step. Here are some resources that will help you learn it:

Free Resources

  • A Cartoon Guide to Redux – this is a great read if you want to know about the different components that make up Redux and how they work together. The visual can really help you in understanding the different concepts better.
  • Learn Redux – from the same guy who created the React for Beginners course. This course will teach you how to create an Instagram clone using React.js, Redux and React Router.
  • Getting Started with Redux – a course from the creator of Redux himself, Dan Abramov. If you’re looking into learning the nitty gritty details of using Redux, this is the course for you. Because it will not only teach how to use Redux within a React app, it will also dive into the details of using the different tools available in Redux.
  • Building React Applications with Idiomatic Redux – in this course you will learn about the production-ready techniques for building React and Redux applications.

Paid Courses

  • Modern React with Redux – learn the basics of React, Redux as well custom components such as Google Maps and charts by developing an app.
  • Advanced React and Redux – learn how to implement authentication, test components and use middlewares.
  • Building Applications with React and Redux in ES6 – an all in one course that shows you how to setup your environment for React development, teach you the basics of React and Redux, and how to test React components and your Redux code.

Redux is pretty much the De facto standard library for managing state in React apps. But that doesn’t mean that you can’t choose to use other solutions.

Other Useful Libraries

Here are other React libraries that you may find useful:

  • React Icons – use popular icon sets (e.g. Fontawesome, Octicons) in React.
  • React i13n – allows you to include instrumentation (analytics) to your app.
  • Omniscient – provides abstraction for React components that allows for fast top-down rendering. This uses immutable.js for immutable data.
  • Search Kit – a collection of UI components for creating beautiful search applications using ElasticSearch.
  • React Motion – an animation library.
  • React Forms – provides a set of tools for React to handle form rendering and validation.
  • react-intl – provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.

Development Tools

As you’re using React, Redux and other libraries you’ll notice that there are things that you need to do repeatedly. Namely writing out common React functions and debugging your code if something goes wrong. In this section we’ll look at some of the tools that you can use to ease up your React development.

Text Editor

Once you’ve gotten used to the React syntax, it’s high time you install plugins that will help you to easily write React specific code. Two of the most popular one’s are Atom and Sublime Text, so we’re going to look at specifically these two. You can start the tooling journey by reading one of the articles below:

Build Tools

Once you’re happy with your text-editor setup, you need to get acquainted with a build tool. If you’ve checked out the Boilerplates section earlier, you might have already introduced yourself to one such build tool: Webpack. Build tools play a role in the development, testing and deployment phase of your application. Here are a few points just to give you an idea on what build tools does:

  • They accept your JSX and ES6 code and spits out JavaScript that’s readable by the browser.
  • They compile all your modules together into a single file that can be linked into your page.
  • They listen to source code changes and use either live reloading or hot module replacement to update the preview of your app in the browser.
  • They run your tests.

Now you know that there’s no escaping build tools when it comes to React development. Of course, in the beginning you can use Create React App and it will handle the compilation of your React code for you. But as soon as you get out of the “beginner zone”, the next thing that you need to learn is how to use a proper build tool. Here are some resources that can help you with that:

Note that Webpack isn’t the only build tool out there. There are lots of other tools that you might want to check out. Webpack is pretty much the De Facto standard when it comes to React apps, that’s why it’s the one that I introduced.

Debugging

Next you need to up your debugging game. That means no more using console.log when you’re trying to find out the cause of an issue.

  • React Dev Tools – allows you to inspect a React Renderer, including the Component hierarchy, props, state, and more. This tool is currently available on Chrome and Firefox.
  • React Inspector – allows you to inspect data in your React apps ala Chrome Dev Tools.
  • Redux DevTools – allows you to inspect state and action payload as they happen. Actions can also be cancelled so you can see the previous state before the action was fired.
  • Reactotron – an OS X app for inspecting your React JS and React Native apps.

Once you’re productive in using your newly found tools. You can start looking for other tools that can help you in developing React apps. Here are a few that you might want to start with:

  • React Storybook – a UI development environment for your React components. It allows you to visualize different states of your UI components and develop them interactively.
  • React Styleguidist – a style guide generator for your React components.

If you want more, Facebook has compiled a list of tools that you can use while developing in React:

Testing

In order to ensure that your code works as expected, you also need to perform tests. Three of the most common one’s are unit tests, functional tests and integration tests. If you’re not aware of any of these, I recommend you to read this article by Eric Elliot on JavaScript Testing: Unit vs Functional vs Integration Tests. That article will teach you everything you need to know about those three types of tests, why they are important, and it will also show some sample codes for each type. Testing also plays a huge role in Continuous Delivery, which is tackled in the Deployment section. Which is why testing plays a very important in the deployment of quality software.

Below are some resources that you can use to get started with your testing adventure. Note that a few of these are for testing JavaScript code in general, not just testing your React code. This is because testing should be holistic. The entirety of the app needs to be tested, so that you get the full benefit.

Testing Articles

  • Writing Testable JavaScript – shows you organize and write your code so that it can be easily tested. This uses Mocha as the test framework, Chai as the assertion library, and jQuery to verify the contents of the page. There’s also a similarly named article which is a good read as well.
  • A Gentle Introduction to JavaScript Test Driven Development – the first part of a three-part series that teaches you how to get started with TDD in JavaScript. In this tutorial, you will be building a simple application which in which you apply TDD. This means that not only do you get to see how to test code, you also get to see the decisions behind why a specific code is written in that specific way.
  • Unit Testing and TDD in Node.js – shows you how to get started in unit testing your Node.js code using Mocha, Chai and Sinon.

Once you have a good feel on how to do unit testing in JavaScript, the next step is to actually apply in your React apps:

Testing Utilities

These are the testing tools that are mentioned in the articles above:

  • Jest – a test runner.
  • Enzyme – a testing utility for React.
  • Mocha – a test framework for JavaScript projects.
  • Nightwatch.js – a functional testing tool. It verifies that the functionality of your app work correctly based on the user’s point of view.

Automated Backend Testing Services

You can use any of these two services for manual and automated cross-browser Selenium testing:

Performance

Now that you’re sure your components really do what you intend them to do. It’s now time to start looking at how to improve the performance of your React apps. Note that in most cases you don’t really need to check the performance of your app. Especially if it’s just a fairly standard app. However, if you have very complicated views you may start looking into your app’s performance. Here are a few signs that your app needs to have a performance evaluation:

  • It needs to work with lots of data.
  • Multiple parts of the app is updated at the same time.
  • It has lots of user interactions which updates the views.

Performance Articles

The following articles will give you an idea on how to get started in performance debugging your React app:

Performance Tools

Here are the tools that you could use for debugging the performance of your React apps:

  • ReactPerfTool – used for debugging the performance of your React application in a visual way.
  • React Render Visualizer – a visual way to see what is rendering and why. Each component is highlighted when they are mounted or when they are updated.
  • Why did you update? – a function that monkey patches React and notifies you in the console when potentially unnecessary re-renders occur.

Explore appendTo’s React Courses

Performance Libraries

There are also some libraries that you can use for optimizing performance:

  • React Static Container – renders static content efficiently by allowing React to short-circuit the reconciliation process.
  • React Fast Click – automatically adds fastclick touch events to elements with onClick attributes (and those that require special functionality, such as inputs) to prevent the delay that occurs on some touch devices.
  • react-lazyload – used for lazyloading components, images, and other parts of your React application.
  • React Infinite – used for optimizing the performance of infinite lists.
  • react virtualized – a collection of React components for efficiently rendering large lists and tabular data.
  • Inferno – an extremely fast, React-like JavaScript library for building modern user interfaces.

Deployment

Finally we get to deployment. This is where you set up continuous integration and deployment. If you’re new to these concepts, continuous integration is a development practice where developers frequently push code into a shared repository (e.g. Git, Mercurial). All the codes are then automatically tested (e.g. unit tests, integration tests) on a staging server. If there are errors and other problems with the code, they’re immediately reported to the developers. All of this is orchestrated by a continuous integration software such as Jenkins. Once the errors are made known to the developers, they can immediately fix the issue and push the updated code. Once all the tests passes, the current build is automatically pushed to the production server.

Continuous Integration Articles

If you’re new to continuous integration, have a read at the following articles:

Continuous Integration and Deployment Software

Now that you know all about the steps involved in continuous integration, it’s now time to pick a continuous integration service. What you pick should be based on the needs of your specific project. For example, if you use pull requests in Github to keep track of a specific change and review the code. You should pick a CI service that can do that.

Here are a few continuous integration services that you can use:

If you want to host your own, you can use the following open-source CI servers:

Cloud Server Provider

React apps are just your ordinary web apps so you can use your existing cloud server provider for deploying:

Continuous Integration in React Apps

After you’ve learned the basics of Continuous Integration, decided which CI service, and picked a cloud server provider to use. The next step is to apply what you’ve learned and actually deploy your React application.

Since day 1 we all know that React doesn’t exist alone. There are other components that may be used in your code. That also includes your back-end code, which is most commonly Node.js. But others might also be using PHP, Ruby, Python or any other server-side language. This means that you should include those in your tests as well.

As you have already learned, the most important part of continuous integration is the testing process. First you test your code locally, and if it passes, you push it to the staging server for another set of tests. If it fails, you go back to step 1 until such time that all the tests passes. Once all the tests passes, only then is the code pushed to production.

But how specifically can we set this up for React applications? Well, by now you should already be proficient in using Webpack, Browserify, or any other module bundler that you decided to use. So it’s only a matter of figuring out how to automatically run tests when you push changes to your staging server, have the CI server generate a report on the results of the test, and automatically push the code to the production server when all the tests passes.

A huge part of your deployment process is handled by the build and testing tools of your choice. As you’ve learned earlier, Webpack is the one that’s most commonly used in React apps. So it is used together with the testing tools to ensure that the app has no errors. If you’ve skipped the Development Tools part, now is a good time to read through that.

Here are a few resources that can help you in filling the blanks. Note that most of these talks about the back-end since there are only a few apps that are purely client-side:

Resources for Further Learning

Now that you’ve learned all of the process involved in developing apps with React, you can now sleep peacefully at night. Or not, because just like everything in life, you never actually stop learning. There’s always something new to learn. This is more true in a field like web development because there’s always something new to look forward to everyday. New frameworks, new libraries, new best practices.

So in this section I’ll provide some resources to get you started in learning some more React stuff.

Articles and Tutorials

Those are just a handful of articles that you ought to read if you want to level up your React skills. And because the web industry constantly moves forward, you can expect things to change in a month or two. Meaning the articles that I’ve linked above might become outdated. So the best way to keep yourself updated is to occassionally check out blogs about React. Medium is a good place to start, because it is where developers gather to share their experiences in building apps with React:

Courses

Explore appendTo’s React Courses

Books

Free

Paid

If you want more, the author of the React book that I mentioned earlier has also compiled a list of books on React:

Talks and Conferences

The React website also compiles videos from the community:

If you want more, there are React conferences around the world which uploads their talks on Youtube:

Again, the React website compiles a list of conferences about React. So if you’re looking into attending a React conference, you can check out this page occassionally:

Videos from previous conferences are also linked in there if they’re available. So even if you can’t personally attend, you can still learn something.

More React Resources

If you’re still hungry for more, check out the following awesome lists on Github:

Conclusion

In this post, you learned all about the things involved in creating a React app. Hopefully this post has helped you in your journey to become a full-fledged React developer.