Monthly Archives: June 2018

Weekly Node.js Update - #26 - 06.29, 2018

By Tamas Kadlecsik

Weekly Node.js Update - #26 - 06.29, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates, projects & tutorials from this week:

Convince Your Boss to Send You to JS Interactive Happening October 10–12 in Vancouver BC, Canada

At JS Interactive, attendees collaborate face-to-face, network, and learn how to better their skills in IoT, backend and frontend. Would you like to join? Here’s how you can convince your boss.

Threads in Node 10.5.0: a practical intro

Node.js 10.5.0 was released a few days ago. One of its main features was the addition of initial (and experimental) thread support.

This is interesting, specially coming from a language that’s always pride itself of not needed threads thanks to it’s fantastic async I/O. So why would we need threads in Node?

Weekly Node.js Update - #26 - 06.29, 2018

Native Extensions for Node.js

In this article you will read about the most important concepts to develop native extensions for Node.js as well as how to build our first native extension with a practical example.

Upgrading to Node v8 has significantly reduced our operating costs

Ably Realtime has recently upgraded from Node.js v6 to v8. Read what improvements they experienced as a result of this upgrade.

“Following an upgrade from Node.js v6 to v8, our bet has paid off. Our latencies are more consistent and our global infrastructure server costs have gone down by almost 40%.”

Hapi vs. Express in 2018: Node.js Framework Comparison

This is the story of the battle between two popular frameworks: Hapi and Express.

There are some key differences you should consider if you’re making a choice between them for a project.

How to build powerful REST APIs blazingly fast with Node.js

How to build powerful REST APIs blazingly fast with Node.js? – Read the story that might save you (and your API consumer) some heartache.

Weekly Node.js Update - #26 - 06.29, 2018

Timing Performance with Performance Hooks in Node.js

In this tutorial, you’ll learn how to use the performance hooks module to get the relevant statistics of writing to and reading data from a file system. Let’s dive in!

Previous Node.js Updates:

In the previous Weekly Node.js Update, we collected great articles, like

  • Node v10.5.0 (Current) Released;
  • How to make beautiful, simple CLI apps with Node;
  • JavaScript Engine V8 release v6.8;
  • End-to-end testing Single Page Apps and Node.js APIs with Cucumber.js and Puppeteer;

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

8 Effective Design Tips for Offline Applications

By Silm Momoh

With the seeming massive adoption of web applications, design systems to support this adoption get better. While the internet is abound in certain areas, connectivity could be limited or non-existent in other areas or cases, this notion has influenced the design of applications on both web and mobile platforms. Poor connectivity influenced the development and speedy adoption of progressive web applications.

Progressive web apps are applications which look and function like mobile applications. Caching techniques, service workers, manifest files and design are certain elements considered when designing for offline applications.

In this post, we shall be discussing 8 tips for effective design of applications required to function offline.

Application States

All digital products (for the most of today) function in two main states, the offline state and the online state.

In the online state, an application is basically connected to the internet and have access to resources available on the internet including real-time information and remote communication. Also, third party services and APIs also have access to the internet. This is the state in which most applications function.

An alternate state is the offline state. In this state, the application is isolated from the internet and functions with resources stored locally or cached during prior connection to the internet. Another similar state considered during design is the state where there is poor or unstable connection.

Offline doesn’t mean ‘no content’

As we try to build for the next billion users, diversity is a factor and we’re beginning to understand and accept that not all users can be online all the time as being online is subject to a lot of factors beyond our control. Offline doesn’t mean ‘no content’. Offline simply means no or poor connection to an internet network.

We live in a disconnected & battery powered world, but our technology and best practices are a leftover from the always connected & steadily powered past. — OfflineFirst

Why do we design offline first?

When it comes to creating digital products, accessibility to users at all times is a major driving factor. Accessibility enabled the adoption of mobile-first design style and with smartphones abound, products have to be built to suit the infrastructure provided by smartphones.

Accessibility drove the development of progressive web applications which function and look like mobile applications. Several web technologies exist which enable the development of cross-platform applications that function on the web, and mobile. An example is the Ionic framework for JavaScript.

As a product or business owner in recent times, you don’t want to lose a potential customer, partner or client because your application works on only a single platform. The same way you don’t want to ruin the experience for users that have poor internet or are in transit and the internet is poor or totally absent. Poor internet connectivity doesn’t necessarily translate to missed notifications on Twitter.

Adopting the offline-first and mobile-first approach when building products go a long way to make sure your product is readily available for most users regardless of device type and internet connectivity.

Offline applications save data. As basic as it sounds, online applications require constant server interaction which directly translates to hosting charges. Reducing the bandwidth usage of an application reduces the hosting charges. This is achieved by efficient UX design and implementation of several offline strategies.

Best Practices & How to adapt to Offline first

Several techniques and best practices are employed while designing offline applications, we shall discuss these below.

Create Awareness

It helps a great deal if you can communicate to the users that they are currently in an offline state. This helps them understand why the product is taking time to display data and clears any thoughts of a faulty product.

Good examples of products that do a good job of showing your Offline status is the YouTube & ProductHunt iOS App as seen in the image below;

Use universal icons

When designing for offline it is great to use universal icons. Icons are a visual representation of an object or action.

Universal icons are icons that are easily recognizable because they have become the industrial standard over time for example the home icon, search icon & location icon.
Universal icons go a long way to make sure users have a great experience using your app.

Also, try to label the icons as it goes the extra step to strip away any ambiguity that might arise. Remember the user is offline which means you can’t offer them support at that particular time. Best equip them as much as you can.

Hold the User’s attention

Sometimes, internet may be temporarily down. You want your users to wait more than they are used to while your product fetches the required data. How you handle this phase is very important.

Google Chrome uses the popular T-Rex dinosaur to keep you on the browser while hoping your internet is restored. You jump over cacti and other hurdles that come along using only Spacebar — very simple and convenient for even non-gamers.

Slack, LinkedIn & YouTube use a skeleton layout loading animation as this usually gives a more optimistic feel than the regular circular & boring loading animation.

Create the ‘Save for offline’ option

In a situation whereby your app uses a bunch of data that doesn’t necessarily change, giving users the option to download this data to the local storage on their device is a great way to improve their experience with today’s technology.

Both Netflix and Google Maps allow you download for offline consumption.
Now imagine you’re in transit and in an internet-dead zone — You can still watch movies in the bus & Google Map your way back home!

Create the ‘Save for later’ option

Scenarios occur whereby your product users absolutely need an internet connection. Maybe it’s to complete a doctor’s appointment or checkout after shopping on your e-commerce store. A good way to handle this is to allow the user perform all the tasks that do not need an internet connection while the rest occurs once connection has been established.

Instagram & WhatsApp typically allow you upload images & send messages respectively while offline and they auto send once the device is connected to the internet again.

Enable Background Refresh or Cache

For Apps that have data that are time-sensitive; a news app or your social media app for instance, the background refresh idea is usually a good option in a situation whereby the internet connection is poor. This allows the App auto-update latest information before you need it & it saves that extra time and frustration of a spotty internet.

Caching is also a good idea especially when your app doesn’t require much data. Browser caching allows assets on your website to be downloaded to the viewer’s local storage temporarily which allows subsequent page loads to be faster as these assets don’t rely on the internet connection anymore.

Customize content

Another way to help your users offline is to customize their content for them. In a situation whereby the user’s internet is poor, you can serve them a lite version of your product & even go as far as disabling images (especially if they are not optimized).

Google Mail does this exceptionally well as it recognizes when your internet is poor and offers you a stripped-down basic version of Gmail to get your stuff done.

Optimize assets

Optimizing images & icons for poor connections is a good practice. Images can disrupt accessibility to your website if they are not properly optimized. Don’t use a larger image or higher resolution size than needed.

Bigger files mean it takes longer for the server to generate that page, and longer for the user to render the page. Avoid TIFF and BMP image files, as they aren’t optimized for web pages. Formats such as Webp, JPEG or PNG files are advised.

Conclusion

And that brings us to the end of the 8 Effective Design Tips for Offline Applications. I hope you learnt a couple of new things and enjoyed yourself in the process. Did I miss anything or you have a couple of questions to ask? Let me know in the comments section right below. Cheers!

Source:: scotch.io

Drawing Parallels Between a Flux-Style State Management Architecture (Like Redux) And An Event-Driven Microservices Architecture

Ben Nadel reflects on all of the Kafka and Redux information that he’s been consuming lately; and, can’t help but start to draw strong parallels between the two architectures. In this post, he looks as the similarities and differences of a microservice system and an Single Page Application (SPA); and, what a Redux application may be able to borrow from a distributed set of microservices….

Source:: bennadel.com

How to use Error Boundaries in React 16

By Ryan Goldman

example fallback UI

Have you seen these in your console?

Cannot read property ‘getHostNode' of null 😱
TypeError: Cannot read property ‘_currentElement' of null 💀

If you maintain a React application, you know that this class of error messages can be among the most frustrating and difficult to resolve. Typical symptoms include stack traces that thread through dark regions of the React internals, devoid of hope or references to even a single line of your own code:

TypeError: Cannot read property 'getHostNode' of null 😱
  at getHostNode(~/react/lib/ReactReconciler.js:64:0)
  at getHostNode(~/react/lib/ReactCompositeComponent.js:383:0) 😕
  at getHostNode(~/react/lib/ReactReconciler.js:64:0)
  at getHostNode(~/react/lib/ReactChildReconciler.js:114:0)😔
  at updateChildren(~/react/lib/ReactMultiChild.js:215:0)
  at _reconcilerUpdateChildren(~/react/lib/ReactMultiChild.js:314:0)
  at _updateChildren(~/react/lib/ReactMultiChild.js:301:0)
  at updateChildren(~/react/lib/ReactDOMComponent.js:942:0)
  at _updateDOMChildren(~/react/lib/ReactDOMComponent.js:760:0) 😞
  at updateComponent(~/react/lib/ReactDOMComponent.js:718:0)
  at receiveComponent(~/react/lib/ReactReconciler.js:126:0)
  at receiveComponent(~/react/lib/ReactCompositeComponent.js:751:0) 😥
  at _updateRenderedComponent(~/react/lib/ReactCompositeComponent.js:721:0)
  at _performComponentUpdate(~/react/lib/ReactCompositeComponent.js:642:0)
  at updateComponent(~/react/lib/ReactCompositeComponent.js:544:0)
  at receiveComponent(~/react/lib/ReactReconciler.js:126:0) 😫
  at receiveComponent(~/react/lib/ReactCompositeComponent.js:751:0)
  at _updateRenderedComponent(~/react/lib/ReactCompositeComponent.js:721:0)
  at _performComponentUpdate(~/react/lib/ReactCompositeComponent.js:642:0)
  at updateComponent(~/react/lib/ReactCompositeComponent.js:544:0)
  at receiveComponent(~/react/lib/ReactReconciler.js:126:0)  😢
  at receiveComponent(~/react/lib/ReactCompositeComponent.js:751:0)
  at _updateRenderedComponent(~/react/lib/ReactCompositeComponent.js:721:0)
  at _performComponentUpdate(~/react/lib/ReactCompositeComponent.js:642:0)
  at updateComponent(~/react/lib/ReactCompositeComponent.js:544:0) 😭
  at receiveComponent(~/react/lib/ReactReconciler.js:126:0)
  at receiveComponent(~/react/lib/ReactCompositeComponent.js:751:0) 😭
  at _updateRenderedComponent(~/react/lib/ReactCompositeComponent.js:721:0)
  at _performComponentUpdate(~/react/lib/ReactCompositeComponent.js:642:0)
  at updateComponent(~/react/lib/ReactCompositeComponent.js:558:0)
  at performUpdateIfNecessary(~/react/lib/ReactReconciler.js:158:0)
  at performUpdateIfNecessary(~/react/lib/ReactUpdates.js:151:0) 😭
  at call(~/react/lib/Transaction.js:138:0)
  at call(~/react/lib/Transaction.js:138:0)
  at call(~/react/lib/ReactUpdates.js:90:0)
  at perform(~/react/lib/ReactUpdates.js:173:0)
  at call(~/react/lib/Transaction.js:204:0)
  at closeAll(~/react/lib/Transaction.js:151:0)
  at perform(~/react/lib/ReactDefaultBatchingStrategy.js:63:0) 💀
  at batchedUpdates(~/react/lib/ReactUpdates.js:98:0)
  at batchedUpdates(~/react/lib/ReactEventListener.js:150:0)

If this type of stack trace from a React error is a familiar sight to you, I’ve got some good news for you!

Say Hello to React 16

React 16 was officially released on September 26, 2017. React 16 is an API-compatible, under-the-hood rewrite of the React internals with ambitious goals like enabling asynchronous or preemptive rendering and providing new tools (with sweet names) for elegantly expressing component hierarchies, like fragments and portals, that are cumbersome today. Another goal of the architecture is handling errors with a new, more correct and rigorous strategy.

This strategy means React 16 prevents situations where an error inside of a render call causes an invalid state and results in undefined behavior or confusing errors (like our good friend Cannot read property 'getHostNode' of null) by unmounting the entire component tree when errors are thrown inside render or lifecycle methods.

Failing more aggressively on these errors means not allowing the application to continue running in a corrupted state — reducing the distance between where you trip (where the real problem occurs) and where you hit the ground (where React blows up because its internal bookkeeping is corrupt). This makes certain errors in React components easier to understand and fix.

However, it also means that existing problems that may have been failing silently or non-catastrophically will now cause the entire app to unmount. Yikes!

The solution to this is React 16’s new tool for explicitly handling error propagation, error boundaries. Error boundaries are analogous to try{ }catch(e){ } statements, but they live inside and are scoped by component hierarchy instead of inside a given block of synchronous JavaScript.

Error boundaries exist because ↓↓↓ doesn’t work with the JSX rendering model:

<div>
  { try {
    <CoolComplicatedComponent/>
  } catch(error){
    handleChildError(error)
    }
  }
</div>

By using error boundaries, you can isolate sections of your app’s component tree from errors in other sections, for instance, allowing your media player to continue running smoothly when the comment section crashes. This is without sacrificing React 16’s more predictable behavior or risking the possible exposure of corrupted state or undefined behavior. It’s a big improvement for your application’s stability.

Start Using Error Boundaries

Error boundaries are something that every large React application should use to improve error resiliency. The API surface of error boundaries is simple: any React component becomes an error boundary when it implements the new lifecycle method, componentDidCatch(error, info). This will be called with any uncaught error that bubbles up from the component’s children’s lifecycle methods, constructors, or render methods (but not the component’s own errors).

<div>
  <ExampleBoundary>
    <h2>Sidebar</h2>
    <Widget/>
  </ExampleBoundary>
  <p> This content won't unmount when Widget throws. </p>
</div>

is a React component that implements componentDidCatch (there’s an example further below).

What to do when you catch errors?

You’re allowed to do whatever you see fit in componentDidCatch. But after it has been triggered, you can’t render this.props.children, and you must replace it with some sort of fallback UI. This fallback might mean rendering a heartfelt apology, a debug view, a feedback form, a link to support, or a funny GIF. It could also mean just discreetly rendering nothing at all — it depends on the needs of your application. Just do yourself a favor and try to ensure it’s not something that will throw its own errors!

Where should Error Boundaries go?

Error boundaries are an open-ended tool, and the community is still defining best practices for them. Our advice is to wrap components at the granularity they can be independently useful. This means that when one errors, the others can still accomplish their purpose. Wrapping your page content will protect your header or sidebar navigation components from being unmounted on an error and will give the user an easy way to back out and return to working parts of your application. By contrast, going to the extreme and wrapping every individual input component of a form could leave someone in a UI state that still responds to their input but can’t actually be used to finish their goal.

Note: by default, raven.js, Sentry’s JavaScript SDK, carefully instruments built-in methods to try to automatically wrap your code in try/catch blocks. It does this to attempt to capture error messages and stack traces from all your scripts, regardless of which origin they’re served from.

Send the errors to Sentry!

Because error boundaries are analogous to try/catch, exceptions they capture will not automatically be bubbled up to Sentry’s global uncaught error handler in production. Make sure to call Raven.captureException(error) in your componentDidCatch implementations to get insights into these errors and fix them.

Here’s an example of an error boundary component that apologizes and sends a report to Sentry plus gives the user the option to fill out a report of what happened:

class ExampleBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  componentDidCatch(error, errorInfo) {
    this.setState({ error });
    Raven.captureException(error, { extra: errorInfo });
  }
  render() {
    if (this.state.error) {
      return (
        <div
          className="snap"
          onClick={() => Raven.lastEventId() && Raven.showReportDialog()}
        >
          <img src={oops} />
          <p>We're sorry — something's gone wrong.</p>
          <p>Our team has been notified, but click here fill out a report.</p>
        </div>
      );
    } else {
      //when there's not an error, render children untouched
      return this.props.children;
    }
  }
}

You can read (or fork!) the complete code here.

One more cool aspect of componentDidCatch is the second argument, errorInfo. Currently, errorInfo has one property, componentStack, which is a component stack trace. That’s the path through your component tree from your application root all the way to the offending component — something that helps map the error location to your mental model and codebase. Because this information is helpful for triaging and resolving errors, we recommend sending it with Sentry errors as extra data.

componentStack as seen in Sentry

As always, you can try Sentry for your React app (it’s 100% open source, too).

That’s it! Happy error monitoring.

Source:: scotch.io

Turbocharge your DevOps workflow by incorporating databases changes

By SergiuHKR

Accelerate DevOps Momentum by Incorporating Database Changes

Surveys indicate you’re probably under serious pressure to deploy new releases and application changes at a rapid pace. Many organizations like yours have adopted or are planning to implement DevOps within the next year. But when application updates require Oracle database changes, the DevOps pipeline screeches to a halt.

The traditional Oracle database change management process creates a major bottleneck in the agile DevOps workflow. It’s time for a better approach.

Database, get ready to join the DevOps party!

How can you make your database development more agile and responsive to changes? What if you could bring database development into the DevOps process via Continuous Database Integration? Imagine if you could:

  1. Ensure all the PL/SQL code in your build performs as expected to help prevent defects making their way into production.
  2. Improve your PL/SQL code quality and maintainability with static code reviews based on predefined rule sets to help minimize future rework.
  3. Perform comparisons of your Oracle database configurations, schema objects and table data between source and target databases and be able to synchronize them.
  4. Promote build artifacts into your target environment with minimum effort.

You’d probably be happy bringing one or two of those tasks into DevOps. Now consider how cool it would be to incorporate all four.

Using automation to catch up with app developers

What if you could automate all those critical tasks? The app team wouldn’t have to wait on you anymore – no more bottleneck. You could implement database changes faster than ever and get a whole lot more out of the DevOps process.

DevOps begins to pay off exponentially when database and application teams are aligned and share the same philosophies and processes. Plus, you can achieve higher code quality in application and database deployments, reducing risks of inefficient application performance and downtime.

Your wishes are granted with Toad® DevOps Toolkit.

You can easily boost the velocity of your DevOps pipeline with Toad DevOps Toolkit. It allows you to execute the most important database development and deployment functions in your DevOps workflow without compromising quality, performance or reliability. By executing these key tasks programmatically from your automation server, such as Jenkins, Bamboo or TFS, Toad DevOps Toolkit enables you to integrate Oracle database with your existing DevOps infrastructure.

Easily integrate database into DevOps

With Toad DevOps Toolkit, you overcome the obstacle of creating tests because it automates the process. Unit tests are created in Toad for Oracle Developer Edition and stored in a repository. Through your automated build process, you define the objects to be tested; the tests are executed and results output in the build console.

Code reviews, simplified

Toad DevOps Toolkit also makes it easier to perform static code reviews based on predefined Toad Code Analysis rules and thresholds. The resulting pass/fail notifications, presented inside the build console, indicate whether the code is ready to be deployed.

Compare and sync

From within your automation server, Toad DevOps Toolkit can compare database configurations, schema objects and table data between two databases (such as dev and test). This process will generate a synchronization script which, when executed, updates the target database to match the source database.

Executing deployment scripts

Once you’re satisfied with the database, schema and data synchronization DDL scripts, you can use Toad DevOps Toolkit to execute one or more deployment scripts. You may specify the output type, error options and the location of the script output. And Toad DevOps Toolkit plays well with virtually any continuous integration and continuous delivery tool, including Jenkins, Bamboo and Team Foundation Server.

Ready to boost the velocity of your DevOps pipeline?

Download a 30-day trial of Toad DevOps Toolkit. This powerful solution brings application and database deployment together, making everyone more agile.

Get a Free Trial of Toad DevOps Toolkit >

Source:: scotch.io

5 Most Common Dropdown Use Cases Solved with React Downshift

By Chris Nwamba

Downshift is a library that helps you build simple, flexible, WAI-ARIA compliant enhanced input React components. Its major use case is for building autocomplete components but it can also be used to build dropdown components.
In this post, we’ll walk through some common use cases solved with Downshift.

Prerequisites

To follow this tutorial, you need Node and NPM installed on your machine. A basic understanding of React will help you get the most out of this tutorial.
If you don’t have Node.js installed, go to the Node website and install the recommended version for your operating system.

Setting up the application

We’ll make use of Create React App to create a simple React app with no build configuration. If you don’t have Create React App installed, run npm i create-react-app in your terminal to install it.
Once you have it on your machine, run the following command to set up a new React project in a directory called downshift-examples and move to this new directory by running these commands:

$ create-react-app downshift-examples
$ cd downshift-examples

Once you’re in the downshift-examples directory, run the following command to install Downshift and some other packages:

$ yarn add downshift axios react-popper

Open the App.css file in the src folder and add the following styles:

    /* src/App.css*/

input {
      margin: 1rem;
      width: 20rem;
      padding: 1rem .5rem;
    }
    .downshift-dropdown {
      margin: 0 auto;
      width: 20rem;
      border: 1px solid whitesmoke;
      border-bottom: none;
    }
    .dropdown-item {
      padding: 0.5rem;
      cursor: pointer;
      border-bottom: 1px solid whitesmoke;
      font-size: 1rem;
      text-align: left;
    }
    .dropdown-button {
      padding: 0.6rem;
      border-radius: 3px;
      background: white;
      cursor: pointer;
    }
    .popper-div {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 5rem;
    }
    .popper-item {
      padding: .5rem;
      border-bottom: 1px solid whitesmoke;
    }

With everything set up, let’s look at some basic Downshift concepts

Basic overview

When using Downshift, the only component we need is . We call the component and pass it some props and it works its magic. Here are some of the most used props:

  1. onChange: This function is called when the user selects an item and the selected item has changed. It returns the selectedItem.
  2. itemToString: This function is used to determine the string value for the selected item which is used to compute the inputValue.
  3. inputValue: This represents the value the input field should have.
  4. getInputProps: This function returns the props you should apply to the input element that you render.
  5. getItemProps: This function returns the props you should apply to any menu item elements you render.
  6. isOpen: This is a boolean that indicates whether or not the menu is open.
  7. selectedItem: This represents the currently selected item input.
  8. render: This is where you render whatever you want to based on the state of Downshift. This function is called with an object.

You can check this link for the full list of props. Now let’s put this knowledge to use.

Basic select field

Our first Downshift use case is a simple select field. Go ahead and create a DownshiftOne.js file in the src folder in the root directory of your app. Add the following code to it:

    // src/DownshiftOne.js

import React from 'react'
import Downshift from 'downshift';

const books = [
      { name: 'Harry Potter' },
      { name: 'Net Moves' },
      { name: 'Half of a yellow sun' },
      { name: 'The Da Vinci Code' },
      { name: 'Born a crime' },
    ];

    const onChange = (selectedBook) => {
      alert(`your favourite book is ${selectedBook.name}`)
    }

    export default () => {
      return (
        <Downshift onChange={onChange} itemToString={books => (books ? books.name : '')}>
          {/* we'll insert a callback here */}
        </DownShift>
      )
    }

In the code above, we import React and Downshift and declare an array of books, an onChange function and also a functional component which returns the component. In the component, we pass the onChange and itemToString props. Inside the component, we’ll pass other props to a callback and render our input field.

Next, we’ll pass the props we need in a callback to the component. Update your functional component with the following:

    // src/DownshiftOne.js
    ...

export default () => {
      return (
        <Downshift onChange={onChange} itemToString={books => (books ? books.name : '')}>
          // pass the downshift props into a callback
          {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => (
            <div>
              // add a label tag and pass our label text to the getLabelProps function
              <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Choose your favourite book</label> <br />
              // add our input element and pass our placeholder to the getInputProps function
              <input {...getInputProps({ placeholder: "Search books" })} />
              // if the input element is open, render the div else render nothing
              {isOpen ? (
                <div className="downshift-dropdown">
                  {
                    // filter the books and return items that match the inputValue
                    books
                      .filter(item => !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase()))
                      // map the return value and return a div
                      .map((item, index) => (
                        <div
                          className="dropdown-item"
                          {...getItemProps({ key: item.name, index, item })}
                          style={{
                            backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                            fontWeight: selectedItem === item ? 'bold' : 'normal',
                          }}>
                          {item.name}
                        </div>
                      ))
                  }
                </div>
              ) : null}
            </div>
          )}
        </Downshift>
      )
    }

In the code snippet above, we passed our Downshift props as parameters to a callback:

{({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => ()}

In the callback, we add our input tag and pass it our getInputProps props:

<input {...getInputProps({ placeholder: "Search books" })} />

Next, we check if the input element is open. If it is, we return a div element containing our menu and return null if it’s not:

{ isOpen ? (<div className="downshift-dropdown">...</div>) : null }

Lastly, in the div element which we’re returning, we basically filter through our books array, returning only the items that include the inputValue. We then map through the filtered books and render them on the page.
Note that we passed the getItemProps function to the div rendered in the map function. It returns the props that we applied while rendering the items.

Let’s import our component to the parent App component, and see our functional select field:

    // src/App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import DownshiftOne from './DownshiftOne'; // import the component

class App extends Component {
      render() {
        return (
          <div className="App">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <h1 className="App-title">Welcome to React</h1>
            </header>
            <DownshiftOne /> // render the component
          </div>
        );
      }
    }
    export default App;

Ensure your server is running by running npm start in your terminal. If you open http://localhost:3000 in your browser, you should see something like this:

Downshift with Axios

In our next example, we’ll use Downshift to create a search field for movies. In the src folder, create a DownshiftTwo.js file and add the following code:

    // src/DownshiftTwo.js

import React, { Component } from 'react'
import Downshift from 'downshift';
import axios from 'axios';

export default class DownshiftTwo extends Component {
      constructor(props) {
        super(props)
        this.state = {
          movies: []
        }
        this.fetchMovies = this.fetchMovies.bind(this)
        this.inputOnChange = this.inputOnChange.bind(this)
      }
      // onChange method for the input field
      inputOnChange(event) {
        if (!event.target.value) {
          return
        }
        this.fetchMovies(event.target.value)
      }
      // input field for the <Downshift /> component
      downshiftOnChange(selectedMovie) {
        alert(`your favourite movie is ${selectedMovie.title}`)
      }
      // method to fetch the movies from the movies API
      fetchMovies(movie) {
        const moviesURL = `https://api.themoviedb.org/3/search/movie?api_key=1b5adf76a72a13bad99b8fc0c68cb085&query=${movie}`;
        axios.get(moviesURL).then(response => {
          this.setState({ movies: response.data.results })
        })
      }
      render() {
        return (
          <Downshift onChange={this.downshiftOnChange} itemToString={item => (item ? item.title : '')}>
          // pass the downshift props into a callback
            {({ selectedItem, getInputProps, getItemProps, highlightedIndex, isOpen, inputValue, getLabelProps }) => (
              <div>
                // add a label tag and pass our label text to the getLabelProps function
                <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Choose your favourite movie</label> <br />
                // add a input tag and pass our placeholder text to the getInputProps function. We also have an onChange eventlistener on the input field
                <input {...getInputProps({
                  placeholder: "Search movies",
                  onChange: this.inputOnChange
                })} />
                // if the input element is open, render the div else render nothing
                {isOpen ? (
                  <div className="downshift-dropdown">
                    {
                      // filter the movies in the state
                      this.state.movies
                        .filter(item => !inputValue || item.title.toLowerCase().includes(inputValue.toLowerCase()))
                        .slice(0, 10) // return just the first ten. Helps improve performance
                        // map the filtered movies and display their title
                        .map((item, index) => (
                          <div
                            className="dropdown-item"
                            {...getItemProps({ key: index, index, item })}
                            style={{
                              backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                              fontWeight: selectedItem === item ? 'bold' : 'normal',
                            }}>
                            {item.title}
                          </div>
                        ))
                    }
                  </div>
                ) : null}
              </div>
            )}
          </Downshift>
        )
      }
    }

In the code above, we have a class component where we’re rendering the component and passing our props to it. In the input field in the component, we have an onChange event listener that listens for new input to the field.
If there’s an input, we call the fetchMovies method which takes the value of the input field and makes an AJAX request to the movies API using Axios. We set the request response to the component state, then filter through them to return the matching item as done in the previous example.

Import and render the component in the parent App component as we did in the previous example. Visit your browser and try searching for your favorite movie:

Dropdown with Downshift

One other use case for Downshift is powering dropdowns. Dropdown’s API helps us build simple dropdown components. Let’s create a DownshiftThree.js file in the src folder and see how to achieve this.
In the DownshiftThree.js file, add the following code:

    // src/DownshiftThree.js

import React, { Component } from 'react'
import Downshift from 'downshift';

export default class DownshiftThree extends Component {
      constructor(props) {
        super(props)
        this.books = [
          { name: 'Harry Potter' },
          { name: 'Net Moves' },
          { name: 'Half of a yellow sun' },
          { name: 'The Da Vinci Code' },
          { name: 'Born a crime' },
        ];

        this.state = {
          // currently selected dropdown item
          selectedBook: ''
        }

        this.onChange = this.onChange.bind(this)
      }

      onChange(selectedBook) {
        this.setState({ selectedBook: selectedBook.name })
      }

      render() {
        return (
          <Downshift onChange={this.onChange} selectedItem={this.state.selectedBook} itemToString={books => (books ? books.name : '')}>
          // pass the downshift props into a callback
            {({ isOpen, getToggleButtonProps, getItemProps, highlightedIndex, selectedItem: dsSelectedItem, getLabelProps }) => (
              <div>
                // add a label tag and pass our label text to the getLabelProps function
                <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Select your favourite book</label> <br />
                // add a button for our dropdown and pass the selected book as its content if there's a selected item
                <button className="dropdown-button" {...getToggleButtonProps()}>
                  {this.state.selectedBook !== '' ? this.state.selectedBook : 'Select a book ...'}
                </button>
                <div style={{ position: 'relative' }}>
                  // if the input element is open, render the div else render nothing
                  {isOpen ? (
                    <div className="downshift-dropdown">
                      {
                        // map through all the books and render them
                        this.books.map((item, index) => (
                          <div
                            className="dropdown-item"
                            {...getItemProps({ key: index, index, item })}
                            style={{
                              backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                              fontWeight: dsSelectedItem === item ? 'bold' : 'normal',
                            }}>
                            {item.name}
                          </div>
                        ))
                      }
                    </div>
                  ) : null}
                </div>
              </div>
            )}
          </Downshift>
        )
      }
    }

In the code above, we have a DownshiftThree class component where we render the component. In the callback passed to it, we have a button where we pass the getToggleButtonProps function. The button houses a ternary operator where we set the content the button based on whether the selectedBook in the component’s state is set.
Next, we call the isOpen prop to see if the dropdown is open or not. If it is open, we map through all the books and render them in the dropdown.

In the onChange method passed to the component, whenever an item is selected, we set it the state, thereby updating the content of the button.
Import and render the component to the parent App component and reload your browser. You should see something like this:

Forms with Downshift

In this example, we’ll be using a Downshift input component as input fields in a form and attempting to submit the form data. In the src directory, let’s create two files: DownshiftInputField.js and DownshiftFour.js.

In the DownshiftInputField.js, we’ll create an input component with Downshift and use it to render some input fields in the DownshiftFour.js file. Let’s create a functional component in our DownshiftInputField.js file:

    // src/DownshiftInputField.js

import React from 'react'
import Downshift from 'downshift';

export default ({ items, onChange, label, placeholder, name }) => {
      return (
        <Downshift onChange={onChange} itemToString={items => (items ? items.name : '')}>
          {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => (
            <div>
            // add a label tag and pass our label text to the getLabelProps function
              <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>{label}</label> <br />
              // add an input tag and pass our placeholder text to the getInputProps function
              <input name={name} {...getInputProps({ placeholder })} />
              // if the input element is open, render the div else render nothing
              {isOpen ? (
                <div className="downshift-dropdown">
                  {
                    items
                      // filter the items and return those that includes the inputValue
                      .filter(item => !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase()))
                      // map through the returned items and render them to the page
                      .map((item, index) => (
                        <div
                          className="dropdown-item"
                          {...getItemProps({ key: item.name, index, item })}
                          style={{
                            backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                            fontWeight: selectedItem === item ? 'bold' : 'normal',
                          }}>
                          {item.name}
                        </div>
                      ))
                  }
                </div>
              ) : null}
            </div>
          )}
        </Downshift>
      )
    }

In the code above, our functional component takes in an array of items, an onChange function, a label and placeholder text and finally a name. The component returns a component which receives all the required props in a callback function. In the callback, we have a label and an input field.
As with other examples, we pass the isOpen prop to a ternary operator. If the input field is open, we filter through the array of items to return items that match the inputValue , then we map through the returned items and render them to the DOM.

Now that our input field component is ready, let’s import it into the DownshiftFour.js file:

    // src/DownshiftFour.js

import React, { Component } from 'react'
import DownshiftInputField from './DownshiftInputField';

export default class DownshiftFour extends Component {
      constructor(props) {
        super(props)
        this.state = {
          books: [
            { name: 'Harry Potter' },
            { name: 'Net Moves' },
            { name: 'Half of a yellow sun' },
            { name: 'The Da Vinci Code' },
            { name: 'Born a crime' },
          ],
          movies: [
            { name: 'Harry Potter' },
            { name: '12 Strong' },
            { name: 'Half of a yellow sun' },
            { name: 'Gringo' },
            { name: 'Black Panther' },
          ],
          book: '',
          movie: ''
        }
        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
      }

      onSubmit(event) {
        event.preventDefault();
        alert(`
        Favourite book: ${this.state.book}
        Favourite movie: ${this.state.movie}
        has been submitted
        `)
      }

      onChange(selectedBook, stateAndHelpers) {
        const element = document.querySelector(`#${stateAndHelpers.id}-input`)
        this.setState({ [element.name]: selectedBook.name })
      }

      render() {
        return (
          <form onSubmit={this.onSubmit}>
            <DownshiftInputField
              items={this.state.books}
              onChange={this.onChange}
              label="Select your favourite book"
              name="book"
              placeholder="Search your favourite book" />
            <DownshiftInputField
              items={this.state.movies}
              onChange={this.onChange}
              label="Select your favourite movie"
              name="movie"
              placeholder="Search your favourite movie" />
            <input type="submit" value="Submit" className="dropdown-button" />
          </form>
        )
      }
    }

In our DownshiftFour.js file, we imported our input field component and created a class component. In our component state, we have an array of books and movies and we render our input field component twice in a form: one as an input field for books and another for movies.

Downshift’s onChange function takes in a second parameter called stateAndHelpers which gives us some information about Downshift’s current state.
In the onChange method, we find the input field the user is currently interacting with by getting it’s id from the stateAndHelpers argument and querying the DOM for it. Once we have the element, we set it to the component state.

When the user hits the submit button, the onSubmit method, gets the selected book and movie from the state and does whatever we want with it.

Import and render the component in the parent App component and let’s give it a spin in the browser. You should have something similar to this:

Downshift with Popper.js

In our last example for this article, we’ll be using Popper.js to change the directions of a Downshift popup. Popper is an awesome library that makes positioning tooltips or popups a straightforward
task. We already installed the react-popper package while setting up the application, so let’s create a DownshiftFive.js file in the src folder.
Let’s add the following code to the new file:

    // src/DownshiftFive.js

import React, { Component } from 'react'
import Downshift from 'downshift';
import { Popper, Manager, Target } from 'react-popper';

export default class DownshiftFive extends Component {
      // define some default props
      static defaultProps = {
        positions: [
          'top',
          'top-start',
          'top-end',
          'bottom-start',
          'bottom',
          'bottom-end',
        ]
      }

      render() {
        return (
          <div className="popper-div">
          // wrap the whole component in Popper's <Manager/> component
            <Manager>
              <Downshift render={({ inputValue, getInputProps, getItemProps, isOpen, selectedItem, highlightedIndex }) => (
                <div>
                // wrap our input element in Popper's <Target/> component
                  <Target>
                    <input {...getInputProps({ placeholder: 'Enter a position' })} />
                  </Target>
                  <div className="downshift-dropdown">
                    {isOpen ? (
                    // pass the selected item to Popper
                      <Popper
                        placement={selectedItem || 'bottom'}
                        style={{ backgroundColor: 'skyblue' }}
                      >
                        {
                        // filter through all the positions and return the ones that include the inputValue
                          this.props.positions
                            .filter(item => !inputValue || item.includes(inputValue.toLowerCase()))
                            // map through all the returned positions and render them
                            .map((item, index) => (
                              <div className="downshift-item popper-item"
                                {...getItemProps({ item })}
                                key={item}
                                style={{
                                  cursor: 'pointer',
                                  backgroundColor: highlightedIndex === index ? '#bed5df' : 'transparent',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                                }}>
                                {item}
                              </div>
                            ))
                        }
                      </Popper>
                    ) : null}
                  </div>
                </div>
              )}></Downshift>
            </Manager>
          </div>
        )
      }
    }

In the code snippet above, we create a DownshiftFive class components with a default position props. These are the positions Popper will use to render our popup. In the render method of the component, we’re returning a component wrapped in a component:

return (
    <div className="popper-div">
    <Manager>
        <Downshift render={({ inputValue, getInputProps, getItemProps, isOpen, selectedItem, highlightedIndex }) => (
        {/* all of our remaining code goes here */}
        )}>
        </DownShift>
      </Manager>
      </div>
    )

The Manager component is a wrapper exposed by Popper that needs to surround all other react-popper components on the page to make them communicate with each other.
If you look closely, you’ll see we’re passing a render prop to the component. This is another way to pass our props to the component. Basically, we moved our callback and passed it to the render prop.
In the callback passed to the render prop, we wrap our input field in a component. This informs Popper that this is the input field around which the popup should be rendered.

Next, we check if our input is open and render a component and pass our selectedItem to it’s placement prop. This helps Popper reposition the popup whenever a new position is selected. Lastly, as with other examples, we filter all the default prop positions, return the positions that include the inputValue, map through them and render them on the page.

Finally, import and render the component in the parent App component and check it out in the browser. You should have something similar to this:

Conclusion

That’s it! In this post, we’ve explored common React dropdown use cases solved with Downshift. I hope you’ve learnt a thing or two.

Source:: scotch.io

Taming The State In React: Your Journey To Master Redux And MobX By Robin Wieruch

Ben Nadel reviews Taming The State In React: Your Journey To Master Redux And MobX by Robin Wieruch. This book iterates through the topic of state management and uses a measured and pragmatic approach to state in a Single Page Application (SPA). This book cleared up a number of questions that Ben Nadel had about Redux, including the what, when, and how of data manipulation and control flow….

Source:: bennadel.com