Monday, September 11, 2017

React Quickly: How to Work with Forms in React

How to Work with Forms in React is an excerpt from React Quickly, a hands-on book by Azat Mardan for anyone who wants to learn React.js fast.

This article covers how to capture text input and input via other form elements like input, textarea, and option. Working with them is paramount to web development, because they allow our applications to receive data (e.g. text) and actions (e.g. clicks) from users.

The source code for the examples in this article is in the ch07 folder of the GitHub repository azat-co/react-quickly. Some demos can be found at http://ift.tt/2kq7Fch.

If you enjoy this post, you might also like to watch our course Build React Forms with Redux.

Recommended Way of Working with Forms in React

In regular HTML, when we work with an input element, the page's DOM maintains that element's value in its DOM node. It's possible to access the value via methods like document.getElementById('email').value, or by using jQuery methods. The DOM is our storage.

In React, when working with forms or any other user input fields, such as standalone text fields or buttons, developers have an interesting problem to solve. From React's documentation:

React components must represent the state of the view at any point in time and not only at initialization time.

React is all about keeping things simple by using declarative styles to describe UIs. React describes the UI, its end stage, and how it should look.

Can you spot a conflict? In the traditional HTML form elements, the state of the elements will change with the user input. React uses a declarative approach to describe the UI. The input needs to be dynamic to reflect the state properly.

If developers opt not to maintain the component state (in JavaScript), or not to sync it with the view, then it adds problems: there might be a situation when internal state and view are different. React won't know about changed state. This can lead to all sorts of trouble, and mitigates the simple philosophy of React. The best practice is to keep React's render() as close to the real DOM as possible, and that includes the data in the form elements.

Consider this example of a text input field. React must include the new value in its render() for that component. Consequently, we need to set the value for our element to new value using value. If we implement an <input> field as we always did it in HTML, React will keep the render() in sync with the real DOM. React won't allow users to change the value. Try it yourself. It drives me nuts, but it's the appropriate behavior for React!

render() {
  return <input type="text" name="title" value="Mr." />
}

The code above represents the view at any state, and the value will always be “Mr.”. With input fields, they must change in response to the user keystrokes. Given these points, let's make the value dynamic.

This is a better implementation, because it'll be updated from the state:

render() {
  return <input type="text" name="title" value={this.state.title} />
}

What is the value of state? React can’t know about users typing in the form elements. Developers need to implement an event handler to capture changes with onChange.

handleChange(event) {
  this.setState({title: event.target.value})
}
render() {
  return <input type="text" name="title" value={this.state.title} onChange={this.handleChange.bind(this)}/>
}

Given these points, the best practice is for developers to implement the following things to sync the internal state with the view (Figure 1):

  1. define elements in render() using values from state
  2. capture changes of a form element using onChange() as they happen
  3. update the internal state in event handler
  4. save new values in state and then update the view with a new render()
Forms in React, Figure 1: Capturing changes in input and applying to state

Figure 1: Capturing changes in input and applying to state

It might seem like a lot of work at first glance, but I hope that by using React more, you'll appreciate this approach. It's called a one-way binding, because state only changes views. There's no trip back, only a one-way trip from state to view. With one-way binding, a library won't update state (or model) automatically. One of the main benefits of one-way binding is that it removes complexity when working with large apps where many views can implicitly update many states (data models) and vice versa—Figure 2.

Simple doesn’t always mean less code. Sometimes, like in this case, developers must write extra code to manually set the data from event handlers to the state (which is rendered to view), but this approach tends to be superior when it comes to complex user interfaces and single-page applications with a myriad of views and states. To put it concisely: simple isn’t always easy.

Forms in React, Figure 2: One-way vs two-way binding

Figure 2: One-way vs two-way binding

Conversely, a two-way binding allows views to change states automatically without developers explicitly implementing it. The two-way binding is how Angular 1 works. Interestingly, Angular 2 borrowed the concept of one-way binding from React and made it the default (you can still have two-way binding explicitly).

[affiliate-section title="Recommended Courses"][affiliate-card title="Job-Ready Angular and TypeScript Training" affiliatename="Todd Motto" text="The ultimate resource to learn Angular and its ecosystem. Use coupon code 'SITEPOINT' at checkout to get 25% off." url="http://ift.tt/2dOQnnQ" imageurl="http://ift.tt/2vNllRn"][/affiliate-section]

For this reason, we’ll cover the recommended approach of working with forms first. It's called controlled components and it ensures that the internal component state is always in sync with the view. The alternative approach is uncontrolled component.

So far, we’ve learned the best practice for working with input fields in React, which is to capture the change and apply it to state as depicted in Figure 1 (input to changed view). Next, let's look at how we define a form and its elements.

Continue reading %React Quickly: How to Work with Forms in React%


by Azat Mardan via SitePoint

Doggo For Hire

Awesome, fun-filled One Pager forming the digital resume of a dog named Birch. There is just so much character from dog emoji-preloaders, confetti shower animations as you scroll, hilarious timelines, fun infographics and an even funnier recognition section. Last shout out to the responsive adaption - especially how the confetti animation moves to the background and how the infographic changes to portrait orientation. Bravo 🐶👏

by Rob Hope via One Page Love

Build a To-Do API With Node and Restify

Introduction

Restify is a Node.js web service framework optimized for building semantically correct RESTful web services ready for production use at scale. In this tutorial, you will learn how to build an API using Restify, and for learning purposes you will build a simple To-Do API.

Set Up the Application

You need to have Node and NPM installed on your machine to follow along with this tutorial.

Mac users can make use of the command below to install Node.

Windows users can hop over to the Node.js download page to download the Node installer.

Ubuntu users can use the commands below.

To show that you have Node installed, open your terminal and run node -v. You should get a prompt telling you the version of Node you have installed.

You do not have not install NPM because it comes with Node. To prove that, run npm -v from your terminal and you will see the version you have installed.

Create a new directory where you will be working from.

Now initialize your package.json by running the command:

You will be making use of a handful of dependencies:

  • Mongoose
  • Mongoose API Query (lightweight Mongoose plugin to help query your REST API)
  • Mongoose TimeStamp (adds createdAt and updatedAt date attributes that get auto-assigned to the most recent create/update timestamps)
  • Lodash
  • Winston (a multi-transport async logging library)
  • Bunyan Winston Adapter (allows the user of the winston logger in restify server without really using bunyan—the default logging library)
  • Restify Errors
  • Restify Plugins

Now go ahead and install the modules.

The packages will be installed in your node_modules folder. Your package.json file should look similar to what I have below.

Before you go ahead, you have to install MongoDB on your machine if you have not done that already. Here is a standard guide to help you in that area. Do not forget to return here when you are done.

When that is done, you need to tell mongo the database you want to use for your application. From your terminal, run:

Now you can go ahead and set up your configuration.

The file should look like this:

Set Up the To-Do Model

Create your to-do model. First, you create a directory called models.

You will need to define your to-do model. Models are defined using the Schema interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. First, you require mongoose, and then you use the Schema constructor to create a new schema interface as I did below. I also made use of two modules called mongooseApiQuery and timestamps.

MongooseApiQuery will be used to query your collection (you will see how that works later on), and timestamps will add created_at and modified_at timestamps for your collection.

The file you just created should look like what I have below.

Set Up the To-Do Routes

Create another directory called routes, and a file called index.js. This is where your routes will be set.

Set it up like so:

The file above does the following:

  • Requires module dependencies installed with NPM.
  • Performs actions based on the request received.
  • Errors are thrown whenever one (or more) is encountered, and logs the errors to the console.
  • Queries the database for to-dos expected for listing all to-dos, and posting to-dos.

Now you can create the entry for your application. Create a file in your working directory called index.js.

You have set up your entry file to do the following:

  • Require modules installed using NPM.
  • Output info level logs to the console using Winston Logger. With this, you get to see all the important interactions happening on your application right on your console.
  • Initialize the server and set up middleware using Restify plugins.
  • bodyParser parses POST bodies to req.body. It automatically uses one of the following parsers based on content type:
    • acceptParser accepts the header.
    • queryParser parses URL query parameters into req.query.
    • fullResponse handles disappeared CORS headers.
  • Next, you start your server and create a mongoose connection. Logs are outputted to the console dependent on the result of creating the mongoose connection.

Start up your node server by running:

Open up postman and send an HTTP POST request. The specified URL should be http://locahost:3000/todos.

For the request body, you can use this:

And you should get a response.

Conclusion

You have been able to build a standard To-Do API using Restify and Node.js. You can enhance the API by adding new features such as descriptions of the to-dos, time of completion, etc.

By building this API, you learned how to create logs using Winston Logger—for more information on Winston, check the official GitHub page. You also made use of Restify plugins, and more are available in the documentation for plugins.

You can dig further into the awesomeness of Restify, starting with the documentation.


by Chinedu Izuchukwu via Envato Tuts+ Code

How to Create Custom Drivers in CodeIgniter

Working as a CodeIgniter developer, you might have come across the concept of a library that enriches the core framework functionality, and CodeIgniter itself provides lots of useful libraries in the core. 

Similarly, a driver is a special kind of library that allows you to add custom features so that the main driver class acts as a parent class and the adapters are treated as child classes.

The best way to understand the concept of drivers is to look at how caching is implemented in the core CodeIgniter framework. The main Cache class acts as a parent class and extends the CI_Driver_Library class. On the other hand, you'll end up finding child classes for APC, Memcached, Redis and the like, implemented as pluggable adapters. The child classes extend the CI_Driver class instead of the main driver class.

The beauty of this approach is that you could easily extend the driver's functionality by adding a new adapter as needed. As in the case of caching, if you need to add a custom caching strategy, you're just a step away from implementing it in the form of a custom adapter.

Creating a custom driver in the CodeIgniter application is the aim of today's article. In the course of that, we'll go through a real-world example that creates a MediaRenderer driver used to render the media from different services like YouTube, Vimeo and similar. The different services will be implemented in the form of adapter classes.

File Setup

The name of the driver that we're going to implement in this article is MediaRenderer. Let's have a quick look at the list of files that are required for the desired setup:

  • application/libraries/MediaRenderer/MediaRendererInterface.php: It's the interface that the adapter needs to implement.
  • application/config/mediarenderer.php: The configuration file that holds our custom driver related settings.
  • application/libraries/MediaRenderer/MediaRenderer.php: It's the class that extends the CI_Driver_Library and is used to operate the different adapters available in the application.
  • application/libraries/MediaRenderer/drivers/MediaRenderer_youtube.php: It's the class that implements the YouTube adapter.
  • application/libraries/MediaRenderer/drivers/MediaRenderer_vimeo.php: It's the class that implements the Vimeo adapter.
  • application/controllers/Media.php: It's the controller class that we'll implement to demonstrate the usage of our custom driver.

So that's the list of files we're going to implement throughout this article.

Create Drivers

In this section, we'll create the base files of our custom driver.

The first thing that we need to do is to define the configuration file of our custom driver. Let's define the application/config/mediarenderer.php file as shown below.

It indicates that we're going to implement two adapters—YouTube and Vimeo. The default adapter is set to YouTube.

Go ahead and create a file application/libraries/MediaRenderer/MediaRendererInterface.php with the following contents.

As you can see, it's a pretty basic interface that makes sure that the adapter that implements this interface must implement the display method.

Next, let's have a look at the MediaRenderer driver file. Go ahead and create a file application/libraries/MediaRenderer/MediaRenderer.php with the following contents.

At the beginning of the file, we include the MediaRendererInterface interface that we've already defined earlier in this section.

As per the CodeIgniter driver standards, our class MediaRenderer extends the CI_Driver_Library class that makes sure that we could easily access driver adapters using the load_driver method defined in the CI_Driver_Library class.

Next, let's have a close look at the constructor.

Recall the mediarenderer configuration file that we defined earlier and that's exactly loaded in the constructor in the first place. It's required that you set the list of adapters that are supported by the driver to the valid_drivers property, so we just did that as well. And finally, we've set the value of the default driver to the _adapter property for our convenience.

Moving further, let's pull in the code of the __get method.

I would say that you're not required to override this method, and our driver would work just fine without it as well. The reason behind the implementation of this method in our case is to enforce the implementation of the MediaRendererInterface interface, and thus it'll make sure that each driver must implement the display method.

Next, let's take a look at the setAdapter method.

As you can see, it's just used to override the default adapter settings in case you want to use a different adapter for the time being.

Finally, there's a display method that calls the display method of the corresponding adapter.

Again, I would say that you can skip the implementation of the display method as you could always call the display method of the adapter directly, as we'll see later in this article. However, I would like to access the adapters via the display method of the MediaRenderer class as this is the place where you could refactor the common code the adapter may implement.

So that was the MediaRenderer class at your disposal.

Create Adapters

We've been discussing the driver adapters for a while, and now it's time to actually implement them.

Let's start with the YouTube adapter file at application/libraries/MediaRenderer/drivers/MediaRenderer_youtube.php.

It's important to note that the adapter name is prefixed with MediaRenderer_, and it also extends the CI_Driver class. Also, it implements the MediaRendererInterface interface to make sure that we adhere to the standards we discussed earlier.

The reason our adapter class extends the CI_Driver class is to avail all the parent methods and properties. You've heard it right, you can access methods and properties of the MediaRenderer class from within the MediaRenderer_youtube class even though it doesn't extend the MediaRenderer class directly.

Apart from that, it's fairly easy to understand the implementation of the display method, which returns the embed code provided that the media ID is passed as an argument of the method.

The Vimeo adapter class is pretty identical to that of YouTube. Go ahead and create one at application/libraries/MediaRenderer/drivers/MediaRenderer_vimeo.php.

And that ends the discussion of adapters.

Putting It All Together

In the last couple of sections, we've discussed the driver and adapter classes. In this section, which is the last one in this article, we'll extend our journey to go through a demonstration of basic driver usage.

Let's start by creating a controller file application/controllers/Media.php.

The first thing that we need to do is to load our custom driver mediaRenderer, and that's what the following snippet does.

To access the custom driver that we've just loaded, you should use the $this->mediarenderer syntax. It's important to note the name of the driver is in lower case, irrespective of the actual driver name.

Next, let's examine what the following code does.

It calls the display method of the MediaRenderer class in the first place, in that it delegates the control to the display method of the corresponding adapter that's set as a default adapter in the mediarenderer configuration file. Eventually, it ends up calling the display method of the YouTube adapter as that's the default adapter in our case.

On the other hand, if you want to call the display method of any specific adapter, you could always do that explicitly, as shown in the following snippet.

As I mentioned earlier, you could also call the display method of any specific adapter directly, without going through the display method of the MediaRenderer class.

So that's how you're supposed to call the driver and its adapters alongside—thanks to the driver structure that allows you to plug in the new adapters on-the-fly as needed.

And that's pretty much it. I hope that you've enjoyed the article, and you could always hit the comment section to express your thoughts and concerns.

Conclusion

A journey through the drivers in the CodeIgniter framework was the recipe of today's article.

As always, the article started with a basic introduction to the concept of drivers in the CodeIgniter framework. As I promised, we went on to create a custom driver based on a real-world use case, and that I believe is the best way to understand a new concept.

I would love to hear if you could come up with something about this exciting concept!


by Sajal Soni via Envato Tuts+ Code

5 Reasons Why Infographics are Effective In Social Media Marketing [infographic]

I would love to share with you a new Infographic about "5 reasons why infographics are effective in social media marketing".

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

Upperquad

We’re Upperquad, an independent creative studio in San Francisco. We build beautiful brands and digital experiences for clients across industries and around the world.
by via Awwwards - Sites of the day

Underscore.js – Utility-Belt Library for JavaScript

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.


by via jQuery-Plugins.net RSS Feed