Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Using React.js on small projects

In this article we will see how to deal with React.js specifically for small projects that are concentrated only in JavaScript and async codes.

Every big fan of accessible technologies suspects whenever he finds a framework or library that "not worth it for a small project" because this is a coded message which means both "It has a wide range of features that a small project will not use", or " it changes the simplicity or the user experience to have performance or other reasons. " Accessibility also helps open source projects out of the dark toward the omnipresence; if jQuery had required a command line tool to compile soon as it was released, it’s almost guaranteed that you would have never heard about it.

With that in mind, we must be fans of JavaScript frameworks that can be used in small projects as well as large ones. It happened before with Angular 1 (Angular 2 does not seem worth it for a small project), but we only had the opportunity to experience React.js in creating a sarcastic complements for web projects worldwide.

Defining the app

My last article was about how many different ways we can write web applications. For this, I did an application that randomly selects a language, framework and data storage and assigns an acronym for this combination.

Getting started with React.js

If you have never used JavaScript before React; i.e. only experienced with Om and Reagent, so while you might have an advantage over broad strokes, you’re still starting from scratch with respect to use with JavaScript.

Even though you’re using Middleman, and unlike last time, choosing to write it in plain-old-js5, partly because CoffeeScript seems to be falling into disuse and we need to reactivate neural connections in JS again. We also decided to not even use the JSX processing React; all DOM in the application would be programmed manually in JavaScript.

First, let’s go to the Techempower Benchmarks and begin our adventure to copy and paste, producing the raw data you can find in this gist. Therefore, we took the react and linked to out index.html. Finally, we started writing a component and setting it up, just like in Listing 1.

Listing 1. Setting up the componente.

var LanguageSelect = React.createClass({
  render: function(){
    var opts = [];
    for(var ii=0; ii<LANGUAGES; ii++){
      opts[ii] = React.createElement(
        "option",
        {value: LANGUAGES[ii]},
        LANGUAGES[ii]
      );
    }
 
    return React.createElement(
      "select",
      {
          value: LANGUAGES[0],
      },
      opts
    );
  }
});
 
ReactDOM.render(
  React.createElement(LanguageSelect),
  document.getElementById("app")
);

That was good for a start. It’s important to notice that once we create React components, this involves the use of React.createClass to define classes and then render them using React.createElement. That part was easy.

Refining things

Then, we set out to make a generic Select element. We take out LanguageSelect and decided that would get a list of options as a property (Be careful of abusing initializeState before learning a little more and decide that the state was not necessary).

We also decided that out constituents would live in a container app where we would store each state that the application would need (a lesson to work with clojurescript react libraries). We also decided that the passage of the state above using onChange events was the best way.

Then, we just made the first container and (after some experimentation) updated out assembly code accordingly to Listing 2.

Listing 2. Updating assembly code.

var App = React.createClass({
    getInitialState: function(){
        return {
            datastore: DATASTORES[0],
            language: LANGUAGES[0],
            framework: FRAMEWORKS_BY_LANGUAGE[LANGUAGES[0]]
        }
    },
 
    setLanguage: function(e){
        this.setState({
            language: e.target.value,
            framework: FRAMEWORKS_BY_LANGUAGE[e.target.value][0]
        })
    },
    setDatastore: function(e){ this.setState({datastore: e.target.value}); },
    setFramework: function(e){ this.setState({framework: e.target.value}); },
 
    render: function(){
        var frameworkOptions = FRAMEWORKS_BY_LANGUAGE[this.props.language];
        var langSelect = React.createElement(
            Select,
            {
                options: LANGUAGES,
                value: this.state.language,
                onChange: this.setLanguage
            }
        );
        return React.DOM.div({},
            React.createElement(Select, {
                options: DATASTORES,
                value: this.state.datastore,
                onChange: this.setDatastore
            }),
            langSelect,
            React.createElement(Select, {
                value: this.state.framework,
                options: frameworkOptions,
                onChange: this.setFramework
            }),
        );
    }
});
 
ReactDOM.render(
  React.createElement(App),
  document.getElementById("app")
);

So, we wrote a Select component for general use, like we can see in Listing 3.

Listing 3. Writing Select component.

var Select = React.createClass({
  updateValue: function(e){
    this.props.onChange(e);
  },
  render: function(){
    var opts = [];
    for(var ii=0; ii<this.props.options.length; ii++){
      opts[ii] = React.createElement(
        "option",
        {value: this.props.options[ii]},
        this.props.options[ii]
      );
    }
    return React.createElement(
      "select",
      {
          value: this.props.value,
          onChange: this.props.onChange
      },
      opts
    );
  }
});

Much better! That is a little more generic.

One thing to know about React is that all you render in your application is a component of the text to the form, the whole thing itself. It is only a component tree in the same way that the DOM is a tree of nodes. So, we needed a component to display the initial cell, and another to show the links that we had carefully collected (Listing 4).

Listing 4. Components to show links.

var VOWELS = "aeiouyAEIOUY";
 
var isVowel = function(s){
    return VOWELS.indexOf(s) > -1;
};
 
var InitialDisplay = React.createClass({
    render: function(){
        var d = this.props.datastore[0],
            l = this.props.language[0],
            f = this.props.framework[0],
            comps = [this.props.datastore, this.props.language, this.props.framework],
            initials = [d, l, f];
            spans = [];
 
        if(isVowel(d)){
            comps = [this.props.language, this.props.datastore, this.props.framework];
            initials = [l, d, f];
        }else if(isVowel(f)){
            comps = [this.props.datastore, this.props.framework, this.props.language];
            initials = [d, f, l];
        }
 
        for(var ii=0; ii<initials.length; ii++){
            spans[ii] = React.createElement("span", {key: ii}, initials[ii]);
        }
 
        return React.DOM.div({},
            React.DOM.h2({},
                "Try the ",
                React.DOM.span({className: "initials"}, spans),
                " stack"
            ),
            React.DOM.section({className: "featuring"},
                "Featuring: ",
                React.createElement(Links, {components: comps}),
                React.DOM.p({}, "Get on the trolley and start writing web applications like it's " + (new Date().getYear() + 1900).toString() + " already!")
            )
        );
    }
});
 
var Links = React.createClass({
    render: function(){
        var links = [];
        for(var ii=0; ii<this.props.components.length; ii++){
            links[ii] = React.DOM.li({},
                React.DOM.a({href: URLS[this.props.components[ii]]},
                    this.props.components[ii]));
        }
        return React.DOM.ul({className: "links"}, links);
    }
});

Here, the InitialDisplay class is responsible for displaying the initials for the selected data storage, language and framework, which are passed as props. It also has some logic that try to put a vowel in the middle of the acronym, if possible. It, in turn, renders the Link component, which only displays each framework/language/storage, as an element with a url like href.

Finally, we just had to install some randomization machines, and update the App to display all the things we just wrote. See Listing 5 for the code needed.

Listing 5. Implementing some randomization.

var App = React.createClass({
    getInitialState: function(){
        return generateRandomState();
    },
    setLanguage: function(e){
        this.setState({
            language: e.target.value,
            framework: pickRandom(FRAMEWORKS_BY_LANGUAGE[e.target.value])
        })
    },
    setDatastore: function(e){ this.setState({datastore: e.target.value}); },
    setFramework: function(e){ this.setState({framework: e.target.value}); },
    randomize: function(){
        this.setState(generateRandomState());
    },
    render: function(){
        var frameworkOptions = FRAMEWORKS_BY_LANGUAGE[this.state.language];
        var langSelect = React.createElement(
            Select,
            {
                options: LANGUAGES,
                value: this.state.language,
                onChange: this.setLanguage
            }
        );
        return React.DOM.div({},
            React.createElement(InitialDisplay, {
                datastore: this.state.datastore,
                language: this.state.language,
                framework: this.state.framework
            }),
            React.DOM.hr(),
            React.DOM.div({className: "selects"},
                React.createElement(Select, {
                    options: DATASTORES,
                    value: this.state.datastore,
                    onChange: this.setDatastore
                }),
                langSelect,
                React.createElement(Select, {
                    value: this.state.framework,
                    options: frameworkOptions,
                    onChange: this.setFramework
                }),
                " or, ",
                React.DOM.a({onClick: this.randomize, href: "#"},
                    "generate a new random stack"
                )
            )
        );
    }
});

Conclusion

First, writing DOM in JavaScript is not something that scale well, and IMO JSX only helps a little. When your entire layout markup is spread around the methods of its component classes, you have a strange distribution of the scattered display code (the best practices generally require to be as close as possible). In Clojurescript, we use kioo to handle it, but it's not an option to React.

That's just an impression, for purposes of this small sample: React is good. In addition, the general GNARliness of JavaScript (especially JS5) is not really so bad. If there was a syntax of loop understanding, most of the code would have been called by react.DOM and React.createElement.

Overall, React.js is a very good option to be used on a small project like this. We could also try the coffee-react for this.



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login