05 Feb

Getting Started with React: Building a Hello World Demo

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

React is quickly becoming the most popular JavaScript library for building user interface (UI) components for HTML/CSS/JS applications. Among a crowded field of frameworks and libraries, it stands out as a simple and efficient approach to building complex, composable UIs that efficiently update the DOM. React was born out of Facebook’s desire to have better UI components for its Facebook and Instagram web applications. [author_more] This post serves as an introduction to a series of blog posts on how to build components with React. The post will explore the assets needed to create React components, examples and explanations of some of the core functionality, as well as comparisons to other JavaScript UI solutions. Additionally, JSX combined with Babel will demonstrate React’s extended syntax, JSX, to simplify the code needed to build HTML and React Component declaratively. React is also cross-browser compatible, and works great in Microsoft Edge.

Hello World

To get started with React.js, let's setup a Hello World demonstration with CodePen. To view the demonstration, and edit the code, please click on the graphic link in the upper left hand corner “Edit on CodePen”.

See the Pen React.js Hello World Demo by SitePoint (@SitePoint) on CodePen.

To setup this CodePen, click on “Settings” in the header, then on “JavaScript”, and you will see, two external JavaScript files were included: React and React-DOM. Both files are referenced from Facebook, and their URLs are:

React: https://fb.me/react-0.14.3.js

React-DOM: https://fb.me/react-dom-0.14.3.js

The first React JavaScript file contains the React library, while the second library React-DOM, contains code to use React with the DOM of a web browser.

Screenshots are from Visual Studio Code

To create React Components, use the createClass function of the React object. The createClass function expects an object configuring the component to be passed in. The createClass function is a helper function for creating new components which inherit from React.Component. If you are using using ES2015 natively in the browser or through a transpiler such as Babel, then it's possible to inherit directly from React.Component using the new class and extends keywords. To use Babel in CodePen, click on “Settings”, then “JavaScript”, and select it from the “JavaScript Preprocessor” drop down list.

See the Pen React.js Hello World ES2015 Demo by SitePoint (@SitePoint) on CodePen.

Regardless of the approach to creating the class structure for the component, the result is the same.

The only required property for a component is the render property, which points to a function object which is used to actually render the DOM of the component. The implementation of the render function introduces a new function, createElement, that is provided by the React object. The createElement function is used to create new DOM elements with React. The function expects up to three parameters.

The first parameter is the name of the HTML element or React Component to create. HTML elements should be a lowercase string containing only the name of the element without the angle brackets and no attributes. Examples of acceptable HTML element arguments include “h1”, “p”, etc. In addition to HTML element names, React Component objects can be passed in. For React Components, the object itself, not a string name of the object, is passed in.

The second parameter is an object of the properties to pass in. For HTML elements, these properties correspond to the attributes of the HTML element. For React Components, these properties correspond to stateless (state will be covered in a future blog post) data for use when rendering the component.

Finally, the third parameter represents the child elements of the element being created. In the “Hello World” example, the child content of the h1 element is the content “Hello World!” In addition to textual content, element objects can be passed in.

See the Pen React.js Child Content Demo by SitePoint (@SitePoint) on CodePen.

Or by using an array, multiple child elements can be passed in as well.

See the Pen React.js Child Content List Demo by SitePoint (@SitePoint) on CodePen.

To utilize the React Components in a web page, the ReactDOM object’s render function is used. It expects an element object, and a root element to which the DOM of the element object will be appended. In the code demonstration, the createElement function is used to create an instance of the HelloWorld component, while document.querySelector is used to select the main element to which the instantiated and rendered HelloWorld component is appended. Once appended, the component appears in the web page, and the React demonstration is complete.

Continue reading %Getting Started with React: Building a Hello World Demo%

05 Feb

Angular 2 Components and Providers: Classes, Factories & Values

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

This is the fourth part in the Angular 2 series. You can read part three here.

In a previous article, we looked at how to get data into and out of components using the @Input and @Output annotations. In this article, we’ll look at another fundamental aspect of Angular 2 components – their ability to use “providers.” You may have seen “providers” in a list of properties you can use to configure components and you might have realized that it allows you to define a set of injectable objects that will be available to the component. That’s nice, but it of course begs the question, “what is a provider?”

Answering that question involves a bit and gets us into a discussion of Angular 2’s Dependency Injection (DI) system. We may specifically cover DI in a future blog post, but it is well covered in a series of articles by Pascal Precht beginning with: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html. We’ll assume you are familiar with DI and Angular 2’s DI’s system in general as covered in Pascal’s article, but in brief the DI system is responsible for:

Registering a class, function or value. These items, in the context of dependency injection, are called “providers” because they result in something. For example, a class is used to provide or result in an instance – see below for more details on provider types. Resolving dependencies between providers – for example, if one provider requires another provider. Making the provider’s result available in code when we ask for it. This process of making the provider result available to a block of code is called “injecting it.” The code that injects the provider results is, logically enough, called an “injector.” Maintaining a hierarchy of injectors so that if a component asks for a provider result from a provider not available in its injector, DI searches up the hierarchy of injectors.

In the previous article, we included a diagram showing that components form a hierarchy beginning with a root component. Let’s add to that diagram to include the injectors and the resources (providers) they register:

Figure 1: Each component has its own injector that registers providers. Injectors create child injectors and a request for a provider starts with the local injector and searches up the injector hierarchy. [author_more] We can see from the above that while components form a downwards directed graph, their associated injectors have a two-way relationship: parent injectors create children (downwards) and when a provider is requested, Angular 2 searches the parent injector (upwards) if it can’t find the requested provider in the component’s own injector. This means that a provider with the same identifier at a lower level will shadow (hide) the same-named provider at a higher level.

What are Providers?

So, what are these “providers” that the injectors are registering at each level? Actually, it is simple: a provider is a resource or JavaScript “thing” that Angular uses to provide (result in, generate) something we want to use:

A class provider generates/provides an instance of the class. A factory provider generates/provides whatever returns when you run a specified function. A value provider doesn’t need to take an action to provide the result like the previous two, it just returns its value.

Unfortunately, the term “provider” is sometimes used to mean both the class, function or value and the thing that results from the provider – a class instance, the function’s return value or the returned value.

Let’s see how we can add a provider to a component by creating a class provider using MyClass, a simple class that will generate the instance we want to use in our application.

Code screenshots are from Visual Studio Code

Figure 2: A simple class with four properties.

Okay, that’s the class; now let’s instruct Angular to use it to register a class provider so we can ask the dependency injection system to give us an instance to use in our code. We’ll create a component, ProvDemo_01.ts that will serve as the root component for our application. We load this component and kick-off our application in the bootstrap.ts:

Figure 3: Our application’s bootstrap.ts file that instantiates the root component.

If the above doesn’t make sense, then take a look at our earlier post that walks through building a simple Angular 2 application. Our root component is called ProvDemo and the repository contains several numbers versions of it. You can change the version that is displayed by updating the line that imports ProvDemo above. Our first version of the root component looks like:

Figure 4: CompDemo with MyClass imported, added to the providers array and used as a Type in the constructor arguments.

Adding the MyClass provider to this component is straightforward:

Import MyClass Add it to the @Component providers property Add an argument of type “MyClass” to the constructor

Under the covers, when Angular instantiates the component, the DI system creates an injector for the component which registers the MyClass provider. Angular then sees the MyClass type specified in the constructor’s argument list and looks up the newly registered MyClass provider and uses it to generate an instance which it assigns to “myClass” (initial small “m”).

The process of looking up the MyClass provider and generating an instance to assign to “myClass” is all Angular. It takes advantage of the TypeScript syntax to know what type to search for but Angular’s injector does the work of looking up and returning the MyClass instance.

Given the above, you might conclude that Angular takes the list of classes in the “providers” array and creates a simple registry used to retrieve the class. But, there is a slight twist to make things more flexible. A key reason why a “twist” is needed is to help us write unit tests for our components that have providers we don’t want to use in the testing environment. In the case of MyClass, there isn’t much reason not to use the real thing but if MyClass made a call to a server to retrieve data, we might not want to or be able to do that in the test environment. To get around this, we need to be able to substitute within ProvDemo a mock MyClass that doesn’t make the server call.

How do we make the substitution? Do we go through all our code and change every MyClass reference to MyClassMock? That’s not efficient and is a poor pattern for writing tests.

We need to swap out the provider implementation without changing our ProvDemo component code. To make this possible, when Angular registers a provider it sets up a map to associate a key (called a “token”) with the actual provider. In our example above, the token and the provider are the same thing: MyClass. Adding MyClass to the providers property in the @Component decorator is shorthand for:

providers: [ provide(MyClass, {useClass: MyClass} ]

which says “register a provider using ‘MyClass’ as the token (key) to find the provider and set the provider to MyClass so when we request the provider, the dependency injection system returns a MyClass instance.” Most of us are used to thinking of keys as being either numbers or strings. But in this case the token (key) is the class itself. We could have also registered the provider using a string for the token as follows:

providers: [ provide(“aStringNameForMyClass”, {useClass: MyClass} ]

So, how does this help us with testing? It means in the test environment we can override the provider registration, effectively doing:

provide(MyClass, {useClass: MyClassMock})

This associates the token (key) MyClass with the class provider MyClassMock. When our code asked the DI system to inject MyClass in testing, we get an instance of MyClassMock which can fake the data call. The net effect is that all our code remains the same and we don’t have to worry about whether the unit test will make a call to a server that might not exist in the test environment.

Continue reading %Angular 2 Components and Providers: Classes, Factories & Values%

05 Feb

5 Tips for Designers New to WordPress

WordPress design opens huge possibilities for both designers and developers. What’s more, you can bet this isn’t just a passing fashion. WordPress is really great and it’s definitely here to stay.

If you haven’t jumped on the WordPress wagon by now, you’ve certainly missed a lot. Don’t worry, it’s never too late to join. If you are a designer – a web designer, or even a graphic one, and you are considering switching to WordPress, here is some advice to help you.

1. Decide If You Can Handle PHP Code

I don’t know if this is true for most designers, but I get the feeling the biggest hurdle they face when they become WordPress designers is code. I don’t remember this being a problem for me back in the day when I first got my hands dirty with WordPress design, but I’d had some coding experience with Java and C before I became interested in WordPress design, so to me PHP wasn’t a monster. Maybe because of this, it’s hard for me to understand how a designer, especially a web designer, who must be familiar with code like HTML and CSS can freak out at the sight of PHP code.

However, I know many designers, some of whom are way better designers than me, who simply can’t deal with this horrible PHP monster. For instance, this article explains why for some (graphic) designers WordPree code (and WordPress itself) is way too much.

Continue reading %5 Tips for Designers New to WordPress%

05 Feb

Building a Pong Clone in Unity: UI and Gameplay

In Part 1 of this tutorial – the Retro Revolution: Building a Pong Clone in Unity – we created a Pong clone with basic artificial intelligence (AI) and almost no user interface (UI).

In this tutorial, we’ll build upon our previously created clone and update it so that it will look identical to classic Pong, have basic UI, and have improved gameplay.

Let’s jump right in, but first, please either go through the original tutorial, or just download the resulting project from GitHub if you’d like to follow along. (You can also view the working demo. Or, if you prefer, play the improved game, which is the result of this article.

Styling the Game

Classic Pong is traditionally black and white, so we must get rid of the colored elements in our Pong.

This also means we need to import new sprites into the Unity project (by dragging them into the Sprites folder in the Assets pane). If you’re following along, feel free to use these examples from the demo code.

After importing the new sprites into Unity, we should select both sprites in the Assets pane and change their pixels per unit to 64. We must also hit Apply for the changes to take effect.

Now that we have our images, we can start updating our Pong Clone. First, we should change the color of the Main Camera’s background to black. This can be done by clicking on the color bar next to the word Background in the Main Camera’s inspector pane. Next, we need to change the color of the paddles. We should select the Player game object in the hierarchy pane and drag the white square sprite into the Sprite attribute’s value in the Sprite Renderer element. Now we should do the same for the Enemy game object.

In order to create the nice middle bar in Pong (see below), we need to create an empty game object (right-click in hierarchy -> create empty) and name it MiddleBar. The Middle Bar game object should have an X of 0 and a Y of 0, so that it’s located in the center of the screen. We can now drag the white square sprite onto the Middle Bar game object to make white squares that are children of the Middle Bar Game object. All of the children’s X scales should be low so that they look like skinny, white sticks.

Finally, we need to change the ball’s sprite so that instead of a grey circle it will be a white circle. If we go to the the ball prefab (located in the Prefabs folder), we can select it and change its sprite as we did with the Player and Enemy, except using the white circle sprite.

Continue reading %Building a Pong Clone in Unity: UI and Gameplay%

05 Feb

3 More Joins You Should Be Familiar With

There are many ways to JOIN data from two database tables and filter the information you require. Craig Buckler wrote a popular piece on understanding JOINs; namely INNER, LEFT, RIGHT, and FULL OUTER. This article is an extension of that one.

Let’s recap these real quick. Picture two tables, one for customers and one for books to establish a book loan database.

customers table

id firstname lastname book_id 1 Joe Blow 1 2 Jane Doe 2 3 Harry Crow 2 4 Jeffrey Snow 0

books table

id Title 1 Star Wars 2 Jurassic Park 3 Little Women 4 Tom Sawyer

The books table has one row for every book.

The customers table has one row for each customer who can only have one book on loan at a time. If they have no book on loan, the book_id would be 0 or an empty string.

This is a very simple example to make the JOINs as clear as possible to understand!

A LEFT JOIN here would be in the case you want to ask a question such as “show me all customers including any books on loan.

You can see in the image that ALL data in the left circle, or table, is included in the result set. Only data that overlaps from the books table is included from the right table. This means that with a LEFT JOIN, some data in the right table may be excluded.

A RIGHT JOIN would be like asking “show me all the books in my library, along with any customers that have borrowed them.

Continue reading %3 More Joins You Should Be Familiar With%

05 Feb

3 More Joins You Should Be Familiar With

There are many ways to JOIN data from two database tables and filter the information you require. Craig Buckler wrote a popular piece on understanding JOINs; namely INNER, LEFT, RIGHT, and FULL OUTER. This article is an extension of that one.

Let’s recap these real quick. Picture two tables, one for customers and one for books to establish a book loan database.

customers table

id firstname lastname book_id 1 Joe Blow 1 2 Jane Doe 2 3 Harry Crow 2 4 Jeffrey Snow 0

books table

id Title 1 Star Wars 2 Jurassic Park 3 Little Women 4 Tom Sawyer

The books table has one row for every book.

The customers table has one row for each customer who can only have one book on loan at a time. If they have no book on loan, the book_id would be 0 or an empty string.

This is a very simple example to make the JOINs as clear as possible to understand!

A LEFT JOIN here would be in the case you want to ask a question such as “show me all customers including any books on loan.

You can see in the image that ALL data in the left circle, or table, is included in the result set. Only data that overlaps from the books table is included from the right table. This means that with a LEFT JOIN, some data in the right table may be excluded.

A RIGHT JOIN would be like asking “show me all the books in my library, along with any customers that have borrowed them.

Continue reading %3 More Joins You Should Be Familiar With%

05 Feb

Using C and C++ Code in an Android App with the NDK

In this tutorial, I will introduce another development option to consider for your next Android project that’s perfect for teams with legacy code or existing knowledge in C and C++. The Android Native Development Kit (NDK) is included in Google’s official toolset and we will look at when the NDK can be useful and how to implement it in an Android app.

Continue reading %Using C and C++ Code in an Android App with the NDK%

05 Feb

Get Your Project Management Professional Certification

Project management is growing more in-demand and more lucrative every day. And a Project Management Professional certification is a must if you're looking to break into the industry. Jumpstart your career with the LearnSmart PMP training at SitePoint Shop—it's now just $49.99, a huge savings of 96% off the regular price of $1,495.

You'll get access to 76+ courses and 35 hours of training that count toward your contact-hour requirement for the PMP exam and certification. Take courses in developing a project schedule, controlling costs, estimating resources, identifying project risks, best practices, and more. You'll have access to the material for a year, so you can work at your own pace to get exam-ready and have plenty of time to revisit the material if you need to brush up on a particular concept.

Start preparing for your new career. Get the LearnSmart PMP training at SitePoint Shop for $49.99.

Continue reading %Get Your Project Management Professional Certification%

05 Feb

Get Your Project Management Professional Certification

Project management is growing more in-demand and more lucrative every day. And a Project Management Professional certification is a must if you're looking to break into the industry. Jumpstart your career with the LearnSmart PMP training at SitePoint Shop—it's now just $49.99, a huge savings of 96% off the regular price of $1,495.

You'll get access to 76+ courses and 35 hours of training that count toward your contact-hour requirement for the PMP exam and certification. Take courses in developing a project schedule, controlling costs, estimating resources, identifying project risks, best practices, and more. You'll have access to the material for a year, so you can work at your own pace to get exam-ready and have plenty of time to revisit the material if you need to brush up on a particular concept.

Start preparing for your new career. Get the LearnSmart PMP training at SitePoint Shop for $49.99.

Continue reading %Get Your Project Management Professional Certification%