Chris Aquino - Big Nerd Ranch Tue, 19 Oct 2021 17:46:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Generators: Rick Astley and the Sequence of Fibonacci https://bignerdranch.com/blog/generators-rick-astley-and-the-sequence-of-fibonacci/ https://bignerdranch.com/blog/generators-rick-astley-and-the-sequence-of-fibonacci/#respond Sun, 11 Sep 2016 10:00:53 +0000 https://nerdranchighq.wpengine.com/blog/generators-rick-astley-and-the-sequence-of-fibonacci/ On the internet, there are two things that are totally played out—Rick Astley and the Fibonnaci sequence. But finally, in one blog post, they have been combined.

The post Generators: Rick Astley and the Sequence of Fibonacci appeared first on Big Nerd Ranch.

]]>

On the internet, there are two things that are totally played out: Rick Astley and
the Fibonacci sequence. But finally, in one blog post, they have been combined. Well. Sort of.

This post is an introduction to JavaScript’s generators, added in ES6, the latest version of JavaScript. This update is also known as “ES2015.”

What is This… Generator?

In a nutshell, generators are functions that can be paused
and resumed. They are useful for things like incrementally
creating very large sequences.

More importantly, they create sequences that are iterators.

The Way of Iteration

If you’ve worked with arrays, you have likely had to iterate
through the elements of that array. There are a few ways you can do this in JavaScript.

One way is to use the very boring (but very fast) for-loop:

let numbers = [0, 1, 1, 2, 3, 5, 8, 13];
for (let index=0; index < numbers.length; index++) {
  console.log(`This number is: ${numbers[index]}`);
}

That snippet of code prints out the first few Fibonacci numbers to the console, as you might expect.

Another way to go through the elements is to use the forEach method
on an array. When you pass a function argument to forEach, forEach will visit each element in the array. As it visits each element, it invokes your
function argument and passes it that element.

let numbers = [0, 1, 1, 2, 3, 5, 8, 13];
numbers.forEach((number) => {
  console.log(`This number is: ${number}`);
});

Here, we’ve passed an anonymous arrow function to forEach, but you can also use named functions or regular (non-arrow) anonymous functions. The arrow function expects
to receive the current item being visited by forEach and gives it the
label number, which is then used inside the body of the arrow function.
Some developers prefer forEach because they find it more expressive than
a for-loop.

Iterating using the for..of syntax

ES6 provides another way of doing iteration: by using for..of.

let numbers = [0, 1, 1, 2, 3, 5, 8, 13];
for (let number of numbers) {
  console.log(`This number is: ${number}`);
}

Like a for-loop, you use the for keyword. But inside of the parentheses, you specify a variable that will point to the current element. Inside the curly braces, you write the body as usual.

Ok, great! Yet another way to work with array elements. Admittedly, it’s
not all that exciting. But, for..of isn’t limited to arrays. You can
create custom iterators that work with for..of.

Building a Custom Iterator

There are two new pieces of syntax that let you create custom iterators:
function * and yield.

Here’s how you would write our not-so-exciting example using that syntax:

function * numbers() {
  yield 0;
  yield 1;
  yield 1;
  yield 2;
  yield 3;
  yield 5;
  yield 8;
  yield 13;
}

for (let number of numbers()) {
  console.log(`This number is: ${number}`);
}

First, you declare a function using the function * syntax.
This tells the JavaScript engine that this function will generate
an iterator. You could say that this is a…generator function.

Some developers prefer to put the * right beside the
function name, like so:

function *numbers() {
  yield 0;
  yield 1;
  yield 1;
  yield 2;
  yield 3;
  yield 5;
  yield 8;
  yield 13;
}

(That is the style that will be used for the rest of this blog post.)

Inside of your generator, you yield at least one value.

When you call a generator, it returns an iterator.
for..of knows to “ask” an iterator for its next value.
The iterator yields its values until there are no more yield
statements.

Obviously, you wouldn’t want to use this syntax to spit
out a bunch of values you could just put into an array.
Let’s continue with the tried and true Fibonacci sequence in the next example.

“Hello, Fibonacci!”

One of the ways you might use generators is to create a sequence
of calculated values. Here is a generator that produces a
sequence of Fibonacci numbers.

function *fibonacci() {
  var n1 = 0;
  var n2 = 1;
  while(true) {
    yield n1; // yield the first number.

    // Calculate the next Fibonacci number
    [n1, n2] = [n2, n1 + n2]; // Destructuring assignment!
  }
}

You might think that calling fibonacci would try to produce
an array of infinite length. But, it doesn’t. It only does enough work to prepare the next value in the sequence.

Notice that the yield is inside of a while(true) statement.
Generators pause their execution until the next time that for..of asks
for another value.

Of course, if you try to iterate over fibonacci with for..of, it will
run forever unless you break out of it. Or, your browser will simply
crash after a few seconds:

Chrome trying to print an infinite sequence

Iterators, Behind the Curtain

So, to recap: generator functions return iterators. But how do iterators work? What exactly is for..of doing with an iterator to get those values out?

To answer that, consider the following generator:

function *roll() {
  yield "Never gonna give you up";
  yield "Never gonna let you down";
  yield "Never gonna run around and desert you";
  yield "Never gonna make you cry";
  yield "Never gonna say goodbye";
  yield "Never gonna tell a lie and hurt you";
}

As mentioned earlier, to get the iterator, simply call the generator.

let rick = roll();

To get the next value, invoke the next function on the iterator,
which will cause it to yield its first value.

rick.next();
// {value: "Never gonna give you up", done: false}

Notice that the value returned is an object with two properties, value and done.
The value property is what the iterator yielded. The done property signals
whether or not there are more values.

If you continue to call rick.next(), you’ll find that the iterator is eventually
drained of its values:

...
rick.next();
// {value: "Never gonna say goodbye", done: false}

rick.next();
// {value: "Never gonna tell a lie and hurt you", done: false}

rick.next();
// {value: undefined, done: true}

When an iterator has no more values to yield, the value property is undefined, while the done property is now true.

Knowing how an iterator works, you could write a simple implementation of for..of
that uses callbacks:

function forOf(iter, callback) {
  let result = iter.next();
  while (!result.done) {
    callback(result.value);
    result = iter.next();
  }
}

And that function could be used like so:

forOf(roll(), (val) => { console.log(val); });

Result of calling our forOf function

Iterable Iterators and Potent Potables

Generators (things that produces iterators) and iterators
(things that can be iterated over) work based on two separate protocols: the iterable protocol and the
iterator protocol.

A generator function is really just syntactic sugar
for implementing the iterable protocol. This protocol
specifies that an object must have a method named
[Symbol.iterator]. (That’s a method whose name
is the ES6 constant Symbol.iterator.)

This [Symbol.iterator] method can return any object, as long
as it is an iterator, meaning that it implements the iterator protocol.

The iterator protocol says that an iterator needs to have
a next method, and that next should return an
object with a value property and a boolean done property.

Here is an example of an object literal version of our
generator function.

let astley = {
  [Symbol.iterator]() {
    return this;
  },
  values: [
    {
      value: "Never gonna give you up",
      done: false
    },
    {
      value: "Never gonna let you down",
      done: false
    },
    {
      value: "Never gonna run around and desert you",
      done: false
    },
    {
      value: "Never gonna make you cry",
      done: false
    },
    {
      value: "Never gonna say goodbye",
      done: false
    },
    {
      value: "Never gonna tell a lie and hurt you",
      done: false
    },
    {
      value: undefined,
      done: true
    }
  ],
  next() {
    return this.values.shift();
  }
};

The [Symbol.iterator] method simply returns a reference to itself, since
it also implements the next method. [Symbol.iterator] is not required
to return this — you are free to make your iterables separate from your
iterators. In this example, we made our iterable and iterator the same object.

You could use your iterable object like so:

for (let lalala of astley) {
  console.log(lalala);
}

The for..of construct implicitly calls astley[Symbol.iterator] to get the iterator object. Then it calls the next method over and over until the
value of the done property is true.

The object literal version is much more verbose than our generator function.
But, it is a good option if you already have an object that encapsulates some
sort of computed sequence and you want to use it with for..of.

Summary

Generators were added to JavaScript in ES6. When combined with for..of, they provide an easy way to create and consume sequences of values.

They have good support in evergreen browsers such as Chrome, Firefox and Edge. In older browsers
(e.g., IE < 9 and Safari < 9), you will want to transpile your code using a tool like Babel.

Stay tuned for upcoming posts about generators and iterators, in which we’ll look at error handling, recursion and coroutines.

The post Generators: Rick Astley and the Sequence of Fibonacci appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/generators-rick-astley-and-the-sequence-of-fibonacci/feed/ 0
How to use Facebook’s React Library to Build UIs, Part 2 https://bignerdranch.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-2/ https://bignerdranch.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-2/#respond Thu, 13 Nov 2014 10:10:22 +0000 https://nerdranchighq.wpengine.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-2/

In my previous post, we created a simple UI component with Facebook’s React library. Now, we’ll create data flows between multiple components.

The post How to use Facebook’s React Library to Build UIs, Part 2 appeared first on Big Nerd Ranch.

]]>

In my previous post, we created a simple UI component with Facebook’s React library. Now, we’ll create data flows between multiple components.

Rot13 encoder app

Let’s build an app that takes the input from a textfield and displays it as rot13.

We’ll structure the app like so:

Data flow diagram for rot13 app

And, the components we’ll build are:

  • Input, for receiving text input.
  • Output, to display the encoded output.
  • App container, which encapsulates the other two components.

It may not be obvious right now, but the container is essential. Every React component must return a single element. In order for us to display both the Input and the Output components, they need to be inside another component.

Laying out our components

We’ll start with our boilerplate HTML, making sure to include the libraries for React and for the JSX Transformer. Remember, when you work with JSX, you need to include the /** @jsx React.DOM */ directive and specify the script’s type as text/jsx.

For each component, we pass in a “spec” object that has a render function.

<!DOCTYPE html>
<html>
  <head>
    <script src="http://fb.me/react-0.10.0.js"></script>
    <script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
  </head>
  <body>
    <div id="container"></div>
    <script type="text/jsx">
      /** @jsx React.DOM */
      var InputComponent = React.createClass({
          render: function () {
          }
      });

      var OutputComponent = React.createClass({
          render: function () {
          }
      });

      var AppComponent = React.createClass({
          render: function () {
          }
      });

      React.renderComponent(
        <AppComponent />,
        document.getElementById('container')
      );
    </script>
  </body>
</html>

Next, we need the render function of our components to return values.

  var InputComponent = React.createClass({
      render: function () {
          return (
              <input></input>
          );
      }
  });

  var OutputComponent = React.createClass({
      render: function () {
          return (
              <div></div>
          );
      }
  });

  var AppComponent = React.createClass({
      render: function () {
          return (
            <div>
                <InputComponent />
                <OutputComponent />
            </div>
          );
      }
  });

  React.renderComponent(
    <AppComponent />,
    document.getElementById('container')
  );

Notice that the AppComponent returns a <div> with the InputComponent and OutputComponents nested inside of them. When the AppComponent’s render function is called, the render functions of the InputComponent and OutputComponent are called as well. This produces a DOM tree roughly equivalent to:

<div>
    <input />
    <div></div>
</div>

One-Way Data Flows

We need a way to get data from one component to another. React has a simple, but sophisticated, system for moving data around. Here is how we might get the static text “Ni hao, React” from our AppComponent to our OutputComponent:

  var InputComponent = React.createClass({
      render: function () {
          return (
            <input></input>
          );
      }
  });

  var OutputComponent = React.createClass({
      render: function () {
          return (
              <div>{ this.props.value }</div>
          );
      }
  });

  var AppComponent = React.createClass({
      render: function () {
          return (
            <div>
                <InputComponent />
                <OutputComponent value="I know kung fu" />
            </div>
          );
      }
  });

  React.renderComponent(
    <AppComponent />,
    document.getElementById('container')
  );

Our AppComponent provides a value attribute to the OutputComponent. Then, the OutputComponent accesses this attribute as a property of this.props.

This is an example of React’s one-way data flow. Every component has access to a props object, and those properties are added to this props object by the parent component. The property names can be any valid JavaScript variable name, and the value can be any valid JavaScript value or expression.

Here, we named the property “value,” but it could have easily been “stringToDisplay” or “outputText.”

To access the value in the OutputComponent’s JSX, you wrap it in single curly braces. This tells the JSX Transformer to evaluate whatever JavaScript expression is inside those curly braces.

State

The values passed from a parent component to a child component do not have to be static. The first step is the let the AppComponent maintain its own store of dynamic data. A state variable, like the props variable, is available to every component. But state is the data that is owned by a component, as opposed to being provided by a parent component.

Let’s update the code so that the AppComponent sets up an initial state object for holding data, and passes some of that data to the OutputComponent.

  var AppComponent = React.createClass({
      getInitialState: function () {
          return {
              value: "I know kung fu!!!!",
          }
      },
      render: function () {
          return (
            <div>
                <InputComponent />
                <OutputComponent value={ this.state.value } />
            </div>
          );
      }
  });

  React.renderComponent(
    <AppComponent />,
    document.getElementById('container')
  );

This code has the equivalent outcome as the previous version, but reveals a little bit more about how to use React effectively. The getInitialState function is called automatically and sets up the state object for a component. We can return any object, and are specifying an object literal for the sake of simplicity.

To pass some of our AppComponent’s state data to the OutputComponent, we use attributes, as we did before. But this time, instead of a static string value, we use the expression this.state.value, wrapped in single curly braces.

Note that we do not wrap { this.state.value } in quotes. If we did that, it would be passing a string, and not the actual JavaScript value we intended.

Events

It’s time to complete our data flow by connecting our InputComponent’s input element to our AppContainer’s state. First, we will watch for the change event on the input.

  var InputComponent = React.createClass({
      _changeHandler: function (event) {
          console.log(event.target.value);
      },
      render: function () {
          return (
            <input
              onChange={ this._changeHandler }
            ></input>
          );
      }
  });

Again, we make use of attributes to declare how our components should interact. Technically, the <input> element is a React component, and we are specifying its onChange attribute. We pass it this._changeHanlder as the value, and we declare a _changeHandler property as part of our component’s spec.

onChange is an attribute that is baked into React. You can find a list of supported event attribute names in the Event System documentation on the React site.

Alternatively, _changeHandler is a name that we made up arbitrarily. One convention that is popular in the React community is to prefix your custom functions with an underscore. This is a good way to communicate that this is a function that you have declared, and is not one of React’s built in component functions.

We define _changeHandler just like any other DOM event handler callback; it should accept a parameter for the event object. Currently, it is only logging the value of the input. To make it do something more interesting, we’ll need to make a couple of changes to the AppComponent.

We will update AppComponent by adding a function that updates its state, and we will pass a reference to this function to InputComponent.

  var AppComponent = React.createClass({
      getInitialState: function () {
          return {
              value: "I know kung fu!!!!",
          }
      },
      _updateValue: function (newValue) {
        this.setState({
            value: newValue
        });
      },
      render: function () {
          return (
            <div>
                <InputComponent sendChange={ this._updateValue }/>
                <OutputComponent value={ this.state.value} />
            </div>
          );
      }
  });

We have created an _updateValue function that calls the built in setState component function. It accepts an object whose properties will overwrite the existing state. When you call setState, you only have to specify the ones you want to update, even if your component’s state has many other properties.

We declare an attribute for InputComponent named sendChange and give it a reference to _updateValue. InputComponent now has access to this function reference in its props object. Let’s use that to complete the data flow.

  var InputComponent = React.createClass({
      _changeHandler: function (event) {
          this.props.sendChange(event.target.value);
      },
      render: function () {
          return (
            <input
              onChange={ this._changeHandler }
            ></input>
          );
      }
  });

Now, when you type into the input field, output updates immediately. Right now, it’s in plain text. Let’s fix that.

And…ROT13!

We need to add our rot13 function to the OutputComponent and call it in our render function.

  var OutputComponent = React.createClass({
      _rot13: function (s) {
          return s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
      },
      render: function () {
          return (
              <div>{ this._rot13(this.props.value) }</div>
          );
      }
  });

Now, our output, though not anywhere near NSA-proof, is unreadable by normal humans. Hooray!

React Components act as neat little boxes that take some input and produce a piece of your UI. Each one has limited responsibilty, which makes it easier for you to reason about your app. While building this app, you learned how to pass data and function references using props and state. Then you made these data flows reactive via Event attributes. Next time, we’ll work on an even larger application and examine the benefits of React over other frameworks.

The post How to use Facebook’s React Library to Build UIs, Part 2 appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-2/feed/ 0
Announcing our Cross-Platform JavaScript Apps with HTML5 bootcamp https://bignerdranch.com/blog/announcing-our-cross-platform-javascript-apps-with-html5-bootcamp/ https://bignerdranch.com/blog/announcing-our-cross-platform-javascript-apps-with-html5-bootcamp/#respond Thu, 10 Jul 2014 22:10:22 +0000 https://nerdranchighq.wpengine.com/blog/announcing-our-cross-platform-javascript-apps-with-html5-bootcamp/

We’re excited to announce that we’ve made our HTML5 Apps with jQuery bootcamp even better. Our new Cross-Platform JavaScript Apps with HTML5 class is more comprehensive and has new content that will take frontend developers to the next level of their careers.

The post Announcing our Cross-Platform JavaScript Apps with HTML5 bootcamp appeared first on Big Nerd Ranch.

]]>

We’re excited to announce that we’ve made our HTML5 Apps with jQuery bootcamp even better. Our new Cross-Platform JavaScript Apps with HTML5 class is more comprehensive and has new content that will take frontend developers to the next level of their careers.

More Comprehensive Content

The updated course addresses the full spectrum of frontend web development skills. It begins with the core skills that a developer will need when making his or her company’s website responsive, or when creating frontend templates for an existing backend. We will then move onto APIs like Geolocation and WebSockets, and then students will learn how to use modern build tools and patterns of application architecture.

Real-World Focus

At every step, students will learn how to coordinate several technologies to implement a real-world feature. The focus of our Cross-Platform JavaScript Apps with HTML5 bootcamp has moved away from individual topics like Functions, Events or CSS. Now, our students will be able to answer a question like: “How do I take some JSON data, build a filterable table of data, and make it display nicely on a wide range of screen sizes?”

In this class, you’ll learn a range of new skills, from the UI-centric (e.g., CSS3 and responsive-web techniques) to more traditional application development chops (such as asynchronous programming, HTML5 APIs and build tools). Plus, you’ll get plenty of practice with tools for responsive layout testing, JavaScript debugging and performance profiling.

Introducing Node.js

We’ve also incorporated Node.js into this course. Learning Node.js empowers students to experiment with end-to-end development. While we won’t be writing big, heavy-duty server code, we will learn how to use certain Node.js-based build tools. For example, students will create a small server program that can host a JavaScript/HTML5 application that will also respond to Ajax requests. Frontend development tools like Yeoman, Grunt, Bower, Gulp and Browserify are Node.js programs—in this class, students will get the necessary hands-on experience to use them effectively.

I will be teaching our next Cross-Platform JavaScript Apps with HTML5 bootcamp at Big Nerd Ranch West in Monterey County, California. Class starts July 28—join us!

The post Announcing our Cross-Platform JavaScript Apps with HTML5 bootcamp appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/announcing-our-cross-platform-javascript-apps-with-html5-bootcamp/feed/ 0
How to use Facebook's React Library to Build UIs, Part 1 https://bignerdranch.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-1/ https://bignerdranch.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-1/#respond Thu, 10 Jul 2014 16:10:22 +0000 https://nerdranchighq.wpengine.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-1/ Facebook's React is a JavaScript library for building high performance User Interfaces. As they like to say, it's the just "V" in MVC. Better yet, it's not a framework. What that means is that React isn't interested in how you handle your data, routing or business logic. The API is refreshingly compact and easy to learn. In the first part of this series of posts, you'll learn how to use React for building a very simple component.

The post How to use Facebook's React Library to Build UIs, Part 1 appeared first on Big Nerd Ranch.

]]>

Facebook’s React library is a JavaScript library for building high performance User Interfaces. As they like to say, it’s the just “V” in MVC. Better yet, it’s not a framework. What that means is that React isn’t interested in how you handle your data, routing or business logic. The API is refreshingly compact and easy to learn. In the first part of this series of posts, you’ll learn how to use React for building a very simple component.

3…2…1…

The main thing you do with React is build UI components. Here’s an example of a component that counts down the seconds until my next birthday. I’ll break it down into steps to make it easier to see how it’s put together.

<!DOCTYPE html>
<html>
  <head>
    <script src="http://fb.me/react-0.10.0.js"></script>
  </head>
  <body>
    <div id="container"></div>
    <script>
      var ExampleApplication = React.createClass({
        render: function() {
          var elapsed = Math.round(this.props.elapsed  / 100);
          var seconds = elapsed / 10 + (elapsed % 10 ? '' : '.0' );
          var message = 'Hooray! Another year in ' + seconds + ' seconds.';
          return React.DOM.h1(null, message);
        }
      });
      var bday = new Date("April 18, 2015 08:12:00");
      setInterval(function() {
        React.renderComponent(
          ExampleApplication({elapsed: bday.getTime() - new Date().getTime()}),
          document.getElementById('container')
        );
      }, 50);
      </script>
  </body>
</html>

The main script consists of two main parts: creating a component and rendering the component. The setInterval is there just to make our countdown timer work.

Creating a component

To create a component, you call React.createClass. Note that this is a plain function call and not a call to a constructor. (Meaning you don’t have to worry about the new keyword.)

  var MyComponent = React.createClass({
  });

createClass takes one argument, an object literal. In the lingo of React, this object is the “spec” for your component. But your spec can’t be empty; you’re required to supply a single property: a render function.

  var MyComponent = React.createClass({
    render: function() {
    }

As you probably guessed, the render function of a component gets called when it needs to be drawn to the screen. But our component doesn’t draw anything. We’ll give it a return value that draws an H1 tag containing the text “Ni hao, React”:

  var MyComponent = React.createClass({
    render: function() {
      return React.DOM.h1(null, "Ni hao, React");
    }
  });

The return statement uses the value produced by the React.DOM.h1(...) call; there are functions in React.DOM corresponding to the other HTML tags as well. The first argument is for providing attributes to the h1, and the second argument specifies the textContent. In this example, we pass null as the first argument, meaning that we aren’t specifying any attributes.

Rendering a component

Rendering a component is as simple as:

  React.renderComponent(
    MyComponent(),
    document.getElementById('example')
  );

The React.renderComponent function takes two arguments. The first arugment is the result of invoking (or “calling”) a component function. The second is the DOM element to render your component to. Pretty simple, no?

You’ll notice a pattern emerging: React is all about functions. React uses a function (React.createClass) to create a component, which is just a function. Then, to render the component, you invoke the React.renderComponent function, and you pass it the result of invoking your component function.

Won’t this get tedious as we create more components? What if we want to use components inside of other components? Will we drown in function calls?

Fear not. They thought about this…

Using JSX to make using React easier

Instead of having to write:

var HelloMessage = React.createClass({
  render: function() {
    return (
      React.DOM.div(null,
        React.DOM.h1(null, "Greetings, Professor ", this.props.name,"."),
            React.DOM.p(null,
              "Would you like to play a game?",React.DOM.br(null ),
              "How about a nice game of",
              React.DOM.a( {href:"http://nsa.gov"}, "Chess"),"?"
            )
      )
    );
  }
});
React.renderComponent(HelloMessage( {name:"Professor Falken"} ), mountNode);

You’d probably rather write:

var HelloMessage = React.createClass({
  render: function() {
    return (
      <div>
        <h1>Greetings, Professor {this.props.name}.</h1>
            <p>
              Would you like to play a game?<br />
              How about a nice game of
              <a href="http://nsa.gov">Chess</a>?
            </p>
      </div>
    );
  }
});
React.renderComponent(<HelloMessage name="Professor Falken" />, mountNode);

I hear you saying, “Waitaminit. Is this PHP or something? Did you trick me?”
It’s not a trick. It’s JSX, which is just embedded XML in your JavaScript. This XML gets transformed into the corresponding React.DOM calls.

Though it’s not required, it makes using React easier on the eyes and has the added benefit of looking like the HTML that will be rendered to the screen.

To use JSX, you have two options. You can either pre-process your JavaScript code (more on this later), or you can include the following script tag:

    <script src="http://fb.me/JSXTransformer-0.10.0.js"></script>

You’ll really only want to use this for development because the XML transformation takes place in the browser, which adds extra overhead and can slow things down if you have a lot of components.

Including the JSXTransformer script will handle your JSX, but only if you modify your script tag a little. You’ve got to change the type and you have to add a comment at the top, like so:

<script type="text/jsx">
  /** @jsx React.DOM
  */
    var HelloMessage = React.createClass({
      render: function() {
        return (
          <div>
            <h1>Greetings, Professor {this.props.name}.</h1>
                <p>
                  Would you like to play a game?<br />
                  How about a nice game of
                  <a href="http://nsa.gov">Chess</a>?
                </p>
          </div>
        );
      }
    });
    React.renderComponent(<HelloMessage name="Professor Falken" />, mountNode);
</script>

The type="text/jsx" tells the browser that it’s not JavaScript, so it shouldn’t try to run it as-is. The comment /** @jsx React.DOM */ instructs the JSXTransformer to turn the XML into React.DOM function calls. These small modifications are a small price to pay for ease of reading.

What’s Next

With Facebook’s React library, it’s easy to create UI components for your web apps. In this post, we introduced the basics of creating a component with React.createClass, using JSX for quicker development and rendering a component with React.renderComponent. In an upcoming post, we’ll create a larger app that shows you how to compose a component hierarchy and create reactive data flows.

Want to know more? In the second post, Chris shows you how to use Facebook’s React library to create data flows between multiple components.

The post How to use Facebook's React Library to Build UIs, Part 1 appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/how-to-use-facebooks-react-library-to-build-uis-part-1/feed/ 0
HTML5 is feature complete. What's next? https://bignerdranch.com/blog/html5-is-feature-complete-whats-next/ https://bignerdranch.com/blog/html5-is-feature-complete-whats-next/#respond Sun, 30 Dec 2012 19:22:26 +0000 https://nerdranchighq.wpengine.com/blog/html5-is-feature-complete-whats-next/

Until just a few days ago, the term “HTML5” referred only to a draft specification. Now that the HTML5 and Canvas 2D specifications have been finalized, what does this mean for developers?

The post HTML5 is feature complete. What's next? appeared first on Big Nerd Ranch.

]]>

Until just a few days ago, the term “HTML5” referred only to a draft specification. Now that the HTML5 and Canvas 2D specifications have been finalized, what does this mean for developers?

  • Developers can feel confident about offering HTML5 web apps and web sites. There is a clear definition of what features to target.

  • Developers can look forward to less and less browser fragmentation in the next few years.

To be honest, it is a smaller milestone than you might think. At the end of the day, it all lies in the hands of browser vendors and their ability to comply with the upcoming standard, due in 2014.

However, HTML5 is the only choice for cross-platform app development, and vendors realize this. HTML5 compliance and performance are the biggest weapons vendors have in the fight for marketshare.

HTML continues to move forward, though. Browser vendors continue to propose and implement new features, and the work on HTML5.1 is already under way.

The post HTML5 is feature complete. What's next? appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/html5-is-feature-complete-whats-next/feed/ 0