My Reaction to React

The interwebs are buzzing about React.js and redux and flux and angular and ember and…

It’s rather tiring to try and learn all of these.

I thought that I’d make a parallel post to this post: Building Your First React.js App.

If you want to use React, fine, I am not trying to convince anyone not to. I just want to show that components in a JavaScript application are quite simple to do and do not require any framework at all to do so.

The concept is to follow the MVC pattern. Where the Models are being observed by the Views which are observed by the Controllers. A user interacts with a View, that event is handled by the Controller which updates the Model accordingly. The View observes the Model and handles those events by rendering itself accordingly. In the aforementioned post, there is no controller, nor events. So I’m going to keep my example as simplistic as the one provided. In a future post, I plan on expanding this idea example to utilize Models and Controllers.

Below is my parallel universe version of Per Harald Borgen’s post:

This article will take you through every step of building the simplest JavaScript app possible. Even simpler than a to-do list.

Why so simple? Because I’ve found that when I’m trying to learn a new technology, even the simplest features can add unnecessary complexity.

If you’re overwhelmed with the wide variety of frameworks and libraries being published, this tutorial is for you.

There are no prerequisites other than basic JavaScript skills. Though if you’d like to read some basic theory before getting started with the coding, you can read the article below and then return.

MDN: JavaScript Guide

Looking at the final project

To claim you’ll be building an app is actually an exaggeration. It’s only a profile page, as you can see below. (The image is taken randomly from http://lorempixel.com/)

Step 1: Splitting the page into components

An application is built around components; everything you see on the screen is a part of a View component. Before we start coding, it’s a good idea to create a sketch of the views, as we’ve done above.

The main component — which wrap all other components — is marked in red. Since we’re targeting this application to run in a browser, we’ll call this one document.body or Body.

Once we’ve figured out that Body is our main viewport, we’ll need to ask ourselves: which view is a direct child of the Body?

I’d argue that the name and the profile image can be grouped into one View, which we’ll call Profile (green rectangle), and the Hobbies section can be another View (blue rectangle).

The structure of our components can also be visualized like this:

- Body
    - Profile
    - Hobbies

We could split the Views further; like ProfileImage and HobbyItem, though we’ll stop here for the sake of simplicity.

Step 2: Hello World

Before you begin coding, you’ll need to download the source file. It’s available at this GitLab repo. Simply copy or clone it and open the index.html file in the browser. (The full code is available in the finished_project.html file.)

I’ve setup the file properly, so you’ll see no links to any unnecessary libraries in the section of the file. Your code will start at line 9.

For a proper JavaScript project, you wouldn’t use this non-minified setup. But I don’t want this tutorial to be about anything else than coding, so we’ll keep it simple.

Let’s write our first View:

As you can see on the first line, we created an object namespace called App. We then created a View object as a component to house all of the views that are going to be in our application. Finally, we declare the Hello object using the Definitive Module Pattern. and the Immediately Invoked Function Expression.

Each View object can have as many members you want, though the most important one is the render method. In the render method, you’ll pass in a reference to the DOM element that will contain the output of this view and then append the contents of the view to that container. In our case, we simply want a div tag with the text “Hello World”.

Then follow up with this inside the App object:

This is how we specify where on the page we want the Hello view to be rendered. This is done by adding a load event handler to the window that calls Hello.render, passing in the document.body as the container parameter. I throw this into a function called main, but that is just a convention that I use due to familiarity with C-based programming languages.

The syntax shouldn’t look to weird, we’re just declaring an object that utilizes the DOM API and adhering to a couple of tried and tested software development patterns.

Load the page in a browser and you’ll see ‘Hello World’ printed out on the screen.

Step 3: More components

Let’s add some more views. Looking back at our application overview, we see that the App component has got two views called Profile and Hobbies.

Let’s write out these two views. We’ll begin with Profile:

There is actually nothing new here. Just a bit more content in the render function than it was in the Hello view.

Let’s write the Hobbies component:

If you refresh the page again though, you won’t see any of these components.

This is because nothing has told these views to render to the screen. We need to update our main function to render the Profile and Hobbies view instead of the Hello view.

This is what we’ll need to do:

If you refresh the page again you’ll see that all the content appears on the page. (Though the image wont appear, as we’ve only added a dummy link to it).

Step 4: Get the data

Now that we have the basic structure setup, we’re ready to add the correct data to our project.

A good practice when implementing the MVC pattern is something called a one directional data flow, meaning that the data is passed down from parent to child components.

Above all the components, paste in the following code:

var DATA = {    
    name: 'John Smith',
    imgURL: 'http://lorempixel.com/200/200/',
    hobbyList: ['coding', 'writing', 'skiing']
}

You can imagine this data being fetched from an API of something.

The next thing you’ll need to do is add this data to the App components as its model.

Data in the MVC pattern is maintained in the Model objects and mutated by the Controller objects. In this simplistic example, I’m going to overlook that aspect and just deal with the single object. In a future post, I’ll explore a more complex data model for the application.

Below, you’ll see how you pass the data into the views, by simply changing the constructor method of the views to accept a model, we’ll initialize our view objects and then render them.

There’s no new syntax, no new Domain Specific Language, just plain old JavaScript.

Now we’re able to access this data from within the View objects through model.[member-name]. We’ll also restructure the views a bit to make the Hobbies a child of the Profile view. This makes it so the application just initializes an instance of the Profile view and data is where it needs to be.

We use the profileImage and name in the Profile view while only the hobbyList array is passed into the Hobbies view. This is because the Hobbies component doesn’t need the rest of the data; it’s simply going to display a list of hobbies.

Let’s look at how we’ll need to rewrite the Profile view in order to use the data we’ve passed down to it:

I removed the IIFE pattern and added the Hobbies view to the Profile‘s members. Then access the members of the passed in model in order to present the resource’s current state to the user.

In the Hobbies component we’ll need to use a technique for looping through the of hobbies.

As you can see, we’re looping through the hobbies array stored in model. We’re using the array prototype method map, which creates a new array based on whatever we return within the callback function.

Notice that I didn’t create a key attribute on the list items. There is no reason to at this point in the development of this application as nothing outside of the Hobbies view is concerned with this list of data as it is presented on the screen.

This is the full code:

full-code.png


Original URL: http://feedproxy.google.com/~r/feedsapi/BwPx/~3/cUjRRF2b8kw/

Original article

Comments are closed.

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑

%d bloggers like this: