Scotch.iohttp://scotch.io/feed
https://cdn.scotch.io/2015/06/scotch-logo-small.pnghttps://cdn.scotch.io/2015/06/scotch-logo-small.pngScotch.iohttp://scotch.io/feed
enFri, 24 May 2019 07:00:13 -0700https://scotch.io/tutorials/implementing-a-scroll-based-animation-with-javascript
https://scotch.io/tutorials/implementing-a-scroll-based-animation-with-javascriptThere is a kind of animations that has not stopped increasing its presence in the most modern and original websites: the animations based on the scroll event of Javascript.
This trend ...]]>There is a kind of animations that has not stopped increasing its presence in the most modern and original websites: the animations based on the scroll event of Javascript.
This trend literally exploded when the parallax effects appeared, and since then its use has become more frequent.

But the truth is that you must be very careful when implementing an animation based on scroll, since it can seriously affect the performance of the website, especially on mobile devices.

That's why we invite you to continue reading the tutorial, where we will implement from scratch and with vanilla Javascript, this beautiful animation based on scroll, also keeping good performance even on mobile devices:

Let's start!

HTML Structure

We will use a simple HTML structure, where each image in the design will actually be a div element in the HTML code, and the images will be defined and positioned with CSS, which will facilitate this task:

<!-- The `.container` element will contain all the images -->
<!-- It will be used also to perform the custom scroll behavior -->
<div class="container">
<!-- Each following `div` correspond to one image -->
<!-- The images will be set using CSS backgrounds -->
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
</div>

Now let's look at the CSS styles needed to achieve the desired design.

Applying CSS styles

First let's start by creating the layout.
This time we will use a CSS Grid, taking advantage of the fact that this technology is already supported in all modern browsers.

// The container for all images
.container {
// 2 columns grid
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 0 10%;
justify-items: end; // This will align all items (images) to the right
// Fixed positioned, so it won't be affected by default scroll
// It will be moved using `transform`, to achieve a custom scroll behavior
position: fixed;
top: 0;
left: 0;
width: 100%;
}

It is important to note that, in addition to the CSS grid, we are giving the .container element a fixed position. This will make this element not affected by the default scroll behavior, allowing to perform custom transforms with Javascript.

Now let's see how to define the styles associated with the images. See the comments for a brief explanation of each part:

And this way we have our design almost ready, we just need to add the background to the body, which we will not explain so as not to extend the tutorial with trivial details.

Note also that for now you will not be able to scroll, since we have given a fixed position to the container element. Next we will solve this problem and bring our design to life :)

Implementing Animations with Javascript

Now let's see how to implement, from scratch and using vanilla Javascript, a custom scroll movement, smoother and suitable for the animations planned. All this we will achieve without trying to reimplement all the work associated with the scroll that the web browser does. Instead, we will keep the native scroll functionality, at the same time that we will have a custom scroll behavior.
Sounds good, huh? Let's see how to do it!

Useful Functions and Variables

First let's look at some useful functions that we will be using. Lean on the comments for a better understanding:

With all this ready, let's see how to implement our custom scroll behavior.

Implementing the Custom Scroll Behavior

To make our webpage scrollable, we will add a new div element to the body dynamically, to which we will set the same height of our container element, in such a way that the scrollable area will be the same.

// The `fakeScroll` is an element to make the page scrollable
// Here we are creating it and appending it to the `body`
var fakeScroll = document.createElement('div')
fakeScroll.className = 'fake-scroll'
document.body.appendChild(fakeScroll)
// In the `setupAnimation` function (below) we will set the `height` properly

We also need a bit of CSS styles so that our .fake-scroll element makes the page scrollable, without interfering with the layout and the other elements:

// The styles for a `div` element (inserted with Javascript)
// Used to make the page scrollable
// Will be setted a proper `height` value using Javascript
.fake-scroll {
position: absolute;
top: 0;
width: 1px;
}

Now let's see the function responsible for calculating all the necessary dimensions, and preparing the ground for the animations:

Easy! Each time the scroll event is triggered, you simply update the target variable with the new position, and call the startAnimation function, which does nothing but start the animation if it is not active yet. Here is the code:

Now let's see the internal behavior for the updateAnimation function, which is the one that actually performs all calculations and transformations in each frame, to achieve the desired animation.
Please follow the comments for a better understanding of the code:

And our custom scroll behavior is ready!
After calling the function setupAnimation, you could scroll as you normally would, and the .container element would be moved in correspondence, but with a very smooth and pleasant effect :)

Then we only have to animate the images in correspondence with the position in which they are with respect to the viewport. Let's see how to do it!

Animating Images While Scrolling

To animate the images we will use the current position of the fake scroll (current), and we will calculate the intersectionRatio (similar to the value from the IntersectionObserver API) between each image and the viewport. Then, we just have to apply the transformations that we want depending on that ratio, and we will obtain the desired animation.

The idea is to show the image without any transformation when it is in the center of the screen (intersectionRatio = 1), and to increase the transformations as the image moves towards the ends of the screen (intersectionRatio = 0).

Pay close attention to the code shown below, especially the part where the intersectionRatio for each image is calculated. This value is essential to then apply the appropriate CSS transformations. Please follow the comments for a better understanding:

Fixing the Jump Issue for Mobile Devices

So far, everything should work perfectly in Desktop, but the story is very different if we try the animation on mobile devices.

The problem occurs when the address bar (and the navigation bar in the footer of some browsers) hides when it is scrolled down, and is shown again when scrolling upwards. This is not a bug, but a feature. The problem appears when we use the CSS unit vh, since in this process that unit is recalculated, resulting in an unwanted jump in our animation.

The workaround that we have implemented is to use the small library vh-fix, which defines, for each element with the class .vh-fix, a static height based on their vh value and the viewport height.
In this way, we should no longer have unwanted jumps :)

Conclusions

And we have finished implementing this beautiful scroll based animation:

Please keep in mind that the objective of this tutorial is essentially academic and to be used as inspiration. To use this demo in production other aspects must be taken into account, such as accessibility, browser support, the use of some debounce function for the scroll and resize events, etc.

Without further ado, we hope you enjoyed it and it has been useful!

Credits

]]>Luis Manuel2019-05-24 07:00:13https://scotch.io/courses/10-web-performance-audit-tips-for-your-next-billion-users-in-2018/tti-time-to-interactive
https://scotch.io/courses/10-web-performance-audit-tips-for-your-next-billion-users-in-2018/tti-time-to-interactiveFirst Meaningful Paint is close to useless because it’s an illusion. It’s a decoy to keep the user from bouncing off your website while we get them the real thing. When does the user get this r...]]>First Meaningful Paint is close to useless because it’s an illusion. It’s a decoy to keep the user from bouncing off your website while we get them the real thing. When does the user get this real thing? That time frame is what we call Time to Interactive. The time when the CPU is idle and the user can start using what ever product you have (remember scrolling is also interaction).

You should be aiming for a 3-5 second TTI.

Given the fact that today’s web pages and sites are considerably heavier than in years past. Websites have matured into vast online ecosystems where a lot of internal and third-party components work together to deliver a cohesive user experience. This implies that there’s simply more content to process and load on today’s sites.

TTI can be subjective. Let’s assume you’re part of the operations management team saddled with the task of monitoring website performance, how do you determine the yardstick for measuring TTI? Will components such as the navigation menu and the sign in link count? And at a time when websites frequently update their content, how can you establish a meaningful baseline against which to measure future performance using TTI?

Performance reliable software such as Amazon Cloudwatch and Microsoft System Center are a great way to measure TTI. Using Visual User Experience (VUX) metrics, they enable you measure how your page is performing. This enables you to measure the time it takes for the first pixels of a page to become visible to the human eye, providing consistent visibility into how long it takes before your users actually perceive the page starting to render. What’s more, there is no subjective determination required to designate what the page’s primary interactive content should be. VUX also provides the total load time for above the fold content, so you can measure how long it takes before your page is fully rendered from your visitor’s perspective.

You should be aiming for a 3-5 second TTI. Once the time exceeds this window, the user might get the feeling that your site is unresponsive and it’s time for him/her to go.

Most of the considerations in FMP would still save you here but the major difference is that FMP buys you more time to calculate and render what else is needed before the user can start using the app.

]]>Chris Nwamba2019-05-21 08:38:58https://scotch.io/tutorials/animated-page-transitions-in-gatsby-websites
https://scotch.io/tutorials/animated-page-transitions-in-gatsby-websitesGatsbyJS is a React-based static site generator powered by GraphQL. It makes it possible for you to code and develop your site, while Gatsby transforms it into a directory with a s...]]>GatsbyJS is a React-based static site generator powered by GraphQL. It makes it possible for you to code and develop your site, while Gatsby transforms it into a directory with a single HTML file with all your static assets. On it’s own Gatsby is fast and comes already preconfigured with service workers, code splitting, server-side rendering, intelligent image loading, asset optimization, and data prefetching. But you already know all of that so let’s get to why we are here.

Sometimes, all of what we just mentioned is still not enough to give your users an amazing experience while visiting your site. At the moment, users demand perfection, and achieving it is almost impossible and comes at incredible costs. In this tutorial, we are going to look at a few through which we can add page transitions to our Gatsby applications to make the site a little bit more interesting and fun.

So far, Gatsby does not do transitions out of the box, hence, the need to take a look at the few things we can do to achieve page transitions in Gatsby applications.

Prerequisites

To get started with this tutorial, you need preliminary knowledge of React.js. This will help you get around with the codes we’ll use here. How best to demonstrate and explain how something works than to actually build it? There’s no better way, as a result, we’ll set up a new Gatsby application and with it, explain the few ways to animate our pages.

Create new Gatsby app

If you haven’t already, go ahead and install the Gatsby CLI tool with the command below:

npm install -g gatsby-cli

With that installed, we can now run Gatsby specific commands to create, build and deploy our applications. To create a new Gatsby project, open a terminal window in your preferred directory and run:

gatsby new transitions-demo

This will create a new Gatsby project for you. You can navigate into the project folder and run the server command to launch the development server.

cd transitions-demo && gatsby develop

This will launch the project on localhost:8000, if you open that up in your browser, you should see your Gatsby project live!

Option 1: Adding page transitions with React transition group

The React transition group is the first and most popular way of adding transitions to Gatsby applications. It is worthy to note that it is not an animation library by design so it doesn’t have the ability to animate styles by itself. Instead it exposes transition stages, manages classes and group elements and manipulates the DOM in useful ways, making the implementation of actual visual transitions much easier.

Install the dependencies

Let’s go ahead and install it and demonstrate how we can leverage it to transition between the pages in our application.

npm install react-transition-group

It will monitor the entery and exit state of elements in the DOM and then apply transitions to them accordingly with respect to our custom transition styles.

The next package we’ll need to install is the Gatsby layout plugin. It gives us the ability to provide a location property required for transitions to work and injects our layout on every page.

npm install gatsby-plugin-layout

Configure Gatsby config

The first we’ll need to do after installing the dependencies is to configure the gatsby-config.js file to use the layout we just installed. Open up the file and add the layout plugin in the plugins array:

For this plugin to work correctly, we need to move the layout file from inside the components folder to the root of our project file src folder and rename the layout.js file to index.js. Then within the components folder, create a new file called transition.js to host our transition logic implementations. Once done, our application structure should look more like this.

Great, now that we have sorted that out, let’s go ahead and implement these transitions in our pages. Open the transition.js file we created in the components folder and update it with this code.

Let’s walk through the code in bits. First, we imported TransitionGroup, and ReactTransition from the react-transition-group package we installed earlier. TransitionGroup helps us manage the mounting and unmounting of components in the DOM while the ReactTransition tracks the entry and exit states of elements passed to it.

Next, we declared a timeout variable that will be responsible for our animation durations. Then we defined the getTransitionStyles object that will contain the CSS styles for our animation. Finally, we destructured children and location from props for ease of usage.

Notice that ReactTransition accepts a key *key*``={``*location.*``pathname} which is how it tracks the entry and exit of elements in the DOM. With that, we apply the styles depending on the status of the page/element (entering, exiting, entered) in the DOM.

That’s it for our transition component. Next thing we need to do is to actually use this component to wrap all our pages. The way it works is that we can wrap all the pages in our application as children in the layout component and then wrap the entire layout component with the transition component.

This way, the location prop we will defined in the the transition component will take effect and animate our pages accordingly as they enter and exit the DOM. Open the index.js file in the layouts folder and update it with the code below.

Here, we imported the Transition component that we created a moment ago, then like we explained earlier, we used it to wrap the children which represents all the pages in our app. We also passed the location prop to the Transition component to track the locations of the pages as they enter and exit the DOM.

Finally, let’s modify the index.js file in our pages folder to add more pages on the homepage so we can test our transitions. Open it and update it with the code below:

Great, now when we run our app, we should see all our pages rendered on the homepage and when we click on any of them, it will transition into the new page as expected.

Option 2: Adding page transitions with Gatsby page transition plugin

What we’ve seen just now is one way to transition pages in Gatsby. Let’s take a look at an entirely different way to do this with a page transition plugin. The gatsby-plugin-page-transitions is a plugin that allows you to declaratively add page transitions, as well as specify custom page transitions for any page on your project.

Just like in the last example, we’ll install the necessary dependencies and try to demonstrate how to add this plugin to our Gatsby app and use it to transition our application’s pages.

Install dependencies

npm install --save gatsby-plugin-page-transitions

Configure Gatsby config

Having installed the plugin, let’s add it to our project through the Gatsby config file in the root of our project. Open the gatsby-config.js and update the plugins array with the code below:

Transition types

The gatsby-plugin-page-transitions plugin _**_provides us with different transition types. There’s

Default transition

Custom Transition

No Transition and

Multiple Transitions

Default transition
Let’s start with the default transition, which is actually the same as what we saw in the last example. All we need to do to get this transition working in our pages is wrap all the pages where we need the transition with the plugin.

To demonstrate this, let’s import the plugin into our Index page and a few other pages in our app and run the app.

Now when we run the app, we get exactly the same transitions we had in our last example since we are using the same transition time of 500ms.

The transition seems a bit too fast according to the demo above, that was intended. The reason is, i wanted to point out the fact that you can set your preferred transition duration for your transitions, the higher the number you set, the slower the transition speed.

Custom transition
The custom transition type gives you the flexibility to determine how you want your pages to transition. The default transition style only performs a kind of reveal animation to transition in any new page, however, there’s so much more you can do with the plugin. For instance you can decide to transition-in pages from the side of the browser, or from the top, zoom pages in and out, swirl pages across the screen and so on.

To do this, you define your custom transition styles with CSS and pass it into the PageTransition element as prop. Here’s how we can change the default transition behaviour in the Index and About pages to a custom sliding transition.

Also make the same update in your about page and run the app again. We should now get the slide transitions working in both pages.

Mixed transition

This should be pretty obvious but yea, you can have more than one transition type in your projects. You can have a different transition for every single page in your app if you so please. The only concern here is that sometimes doing a bit too much is bad for user experience.

It’s always best to keep it neat and simple, however if for any reason you decide to implement different transitions in different pages, all you need to do is style your PageTransition elements separately and boom! you’ll have different transitions for different pages.

Final thoughts

If your application’s pages are filled with contents that will require your users to scroll all the way down to the bottom of your pages, you may experience some weird behaviours when your pages transition in and out. Why? Because by default, when there are enough elements on the page, it jumps to the top of the page first before triggering transitions.

What we can do to fix this is set a time out for the transition so it can wait for the transition to be executed before the page scrolls to the top. Here’s how we do that, open the gatsby-browser.js file in the application’s root directory and update it with this code:

In this post, we have gone through the various ways you can implement page transitions in your Gatsby projects. In the process we looked at how to set up a new Gatsby project from scratch, how to install the necessary dependencies for the transitions and how to use them to build pages.

The two approaches discussed here is not final, maybe there is a better way or a better tool out there that we can use to achieve most of this functionalities. Feel free to mention them so we can all learn and build better products for our users. You can find the source code for this project here. Switch between branches for the transition demonstrations.

]]>Chris Nwamba2019-05-21 08:00:07https://scotch.io/tutorials/build-an-ionic-4-app-with-user-login-and-registration
https://scotch.io/tutorials/build-an-ionic-4-app-with-user-login-and-registrationIonic allows you to develop Progressive Web Applications (PWAs) and hybrid mobile apps. PWAs are web applications that run in a browser and allow for offline capabilities via service workers. They ...]]>Ionic allows you to develop Progressive Web Applications (PWAs) and hybrid mobile apps. PWAs are web applications that run in a browser and allow for offline capabilities via service workers. They can be installed on desktops and mobile devices, just like you install apps on your smartphone. Hybrid mobile apps are like native mobile apps, except they're built using web technologies.

Ionic 2 was based on AngularJS. Ionic 3 was based on Angular. Ionic 4 allows you to use the most popular JavaScript frameworks available today: Angular, React, or Vue. This article focuses on the Angular version of Ionic 4. I'll show you how to create an Ionic 4 app, add user authentication, and configure things to allow user registration.

Get Started with Ionic 4

Create an Ionic 4 Application

From a terminal window, create a new application using the following command:

ionic start ionic-login tabs

When prompted to install the Ionic Pro SDK, answer no.

It may take a minute or two to create your project, depending on the speed of your internet connection.

Once the process completes, start your Ionic 4 application.

cd ionic-login
ionic serve

This command will open your default browser and navigate to http://localhost:8100.

You can use Chrome's device toolbar to see what the application will look like on an iPhone X.

Now let's add a user login feature! Stop the ionic serve process using Ctrl+C before proceeding to the next step.

Add User Login

Schematics is a library from the Angular CLI project that allows you to manipulate projects with code. You can create/update files and add dependencies to any project that has a package.json file. I created an OktaDev Schematics project that makes it possible to add authentication to an Ionic 4 app using one command.

ng add @oktadev/schematics

Before you run this command, you'll need to create an OpenID Connect (OIDC) app in Okta. OIDC builds on top of the OAuth 2.0 authorization framework. It allows clients to verify the identity of the user and get their details. If you're not familiar with OAuth 2.0 or OIDC, I recommend you read What the Heck is OAuth?

Create an OpenID Connect App in Okta

To integrate Okta's Identity Cloud for user authentication, you'll need to signup for a developer account.

You'll need to configure code signing in the General tab, then you should be able to run in Simulator. Below are screenshots of it running on an emulated iPhone X.

Run Your Ionic 4 App on Android

The most important thing to know when running your Ionic app on Android is that you need Java 8 installed. Anything above Java 8 will not work. If you need to switch between Java SDK versions -- like I often do -- I recommend installing SDKMAN! I ran the command below to downgrade from Java 11 to Java 8 in my terminal window:

sdk use java 8.0.202-amzn

You can then generate an Android project.

ionic cordova prepare android

When prompted to install the android platform, answer yes. After this process completes, open your platforms/android directory as a project in Android Studio.

studio platforms/android

NOTE: You will need to have Android Studio 3.3+ installed and have run Tools > Create Command-line Launcher for the command above to work.

Running with Android Studio 3.3.2

When I first tried this in Android Studio, I received a Gradle Sync error:

The minSdk version should be declared in the android manifest file.

In the right pane, it offered a link for me to click on to fix the issue. I clicked on it, then clicked Do Refactor.

I was prompted to update Gradle and clicked Update.

After these changes, my app showed up in the top toolbar.

Running with Android Studio 3.4

When I tried opening the project in Android Studio 3.4, I was prompted to update Gradle again.

After doing so, I received the following error:

WARNING: The following project options are deprecated and have been removed:
android.useDeprecatedNdk
NdkCompile is no longer supported

I found an open issue in the Cordova Android project that shows how to fix it. Open android/gradle.properties and turn off useDeprecatedNdk.

android.useDeprecatedNdk=false

Set LaunchMode to singleTask

You need to make one additional change for everything to work properly on Android. You need to set the launchMode from singleTop to singleTask so the URL does not trigger a new instance of the app. Edit platforms/android/app/src/main/AndroidManifest.xml to make this change:

Now you should be able to click the play button in Android Studio to start your app.

You will be prompted to select an existing AVD (Android Virtual Device) or you can plug in your Android phone and use that. If you have neither, click the Create New Virtual Device Button.

Below are screenshots of the app running on a Pixel 2 AVD.

What About Capacitor?

Capacitor is a project from the Ionic folks that offers an alternative to Cordova. It's currently in beta. The OktaDev Schematics project provides support for Capacitor with a --platform=capacitor flag. For example:

Bonus: You're Using PKCE in the Browser and on Mobile!

The Ionic 4 AppAuth integration in this example uses PKCE (Proof Key for Code Exchange). PKCE (pronounced "pixy") is a security extension for OAuth 2.0 for public clients on mobile (and desktop) clients. It's designed to prevent interception of the authorization code by a malicious application that runs on the same device. You can read about why it's awesome in Aaron Parecki's Is the OAuth 2.0 Implicit Flow Dead?

Learn More About Ionic, Schematics, and Angular

This tutorial showed you how to create an Ionic 4 application and add user login and registration with a handful of commands. If you'd like to see the completed application, you can find it on GitHub.

Ionic's support for React and Vue are in beta at the time of this writing. To read more about them, I recommend the following blog posts:

I could have shown you how to create 19 files and update 8 to integrate OIDC login in Ionic 4. However, that seems like a long and cruel tutorial. Instead, I streamlined everything by using OktaDev Schematics. The code that OktaDev Schematics uses is from the Ionic AppAuth project's
Cordova and Capacitor examples.

I've written a few other tutorials on Schematics that might interest you:

Enjoyed this tutorial? Follow me on Twitter @mraible for more like it!

]]>Matt Raible2019-05-20 12:34:04https://scotch.io/courses/10-react-challenges-beginner/dom-movement-with-events
https://scotch.io/courses/10-react-challenges-beginner/dom-movement-with-eventsStyling elements or in some instances, components in a React project is essential. Sometimes, you need to make a change in the style of an element bas...]]>Styling elements or in some instances, components in a React project is essential. Sometimes, you need to make a change in the style of an element based on changes in the application using JavaScript.

In this challenge, we will change a CSS property when a certain event is fired or a state value in the application is changed.

Bonus Points

Hint

Look up the transform CSS property as well as its corresponding translateY function.

The Solution: Move Box Upward

Various CSS-in-JS solution exists which enable you to write CSS in JavaScript files. In this React challenge, we will update the value of a CSS property in a component using JavaScript.

For this challenge, we are required to move a provided box upwards on the click of a button. This button when clicked updates a created state value and this value is passed to the transform CSS property of the box.

The translateY function is used to displace the box in the 2D plane. This challenge is completed in 3 steps:

Store offset value in state.

Create a function to decrement the offset value.

Bind the offset value to the box and the function to the trigger button.

Store Offset value in State

The useState React hook is used to create a state variable alongside its corresponding update method. The initial value of offsetTop is 300. This initial value will serve as the offset from the original position of the box vertically.

Create a state variable named offsetTop in the App() component and set the initial value to 300. Do this with:

Decrement offsetTop

To move the box closer to the top, reduce the value of offsetTop. Create a function which reduces its value by 50. You can use any value you want. 50 allows the box to move a good amount. Do this in App() with:

The moveBoxUp function will be called whenever the "Move Up" button is clicked.

Bind Data to Box and Button

We now have the transformation data with which we can move the box upward. Add an in-line style with a transformation property and its value which uses the translateY function to displace the box from the top. Do this with:

]]>Chris Sevilleja2019-05-20 12:10:32https://scotch.io/courses/10-react-challenges-beginner/adding-calculator
https://scotch.io/courses/10-react-challenges-beginner/adding-calculatorStoring data in a front-end application and reusing the stored data throughout the application or app component, is an essential piece of modern front-end applications.

CodePen Final...]]>

Storing data in a front-end application and reusing the stored data throughout the application or app component, is an essential piece of modern front-end applications.

We set the default values of the numbers to 0 and the total to the sum of both numbers, which by default is zero as well.

Now we can store and retrieve the value of the numbers to be added in state, proceed to assign these data values to the input element. Also, the value of the data stored in state would be updated from the input using the onChange input event. In the returned JSX of the App() component, specify the value and onChange attributes of the input elements with:

Tailwind is a utility-based CSS framework that just hit a big milestone: v1!!!

Tailwind’s approach to a CSS framework comes in the form of a configurable utility CSS generation based on PostCSS. While I would love to get into the nitty-gritty, there’s already a great article titled Introducing Tailwind.

Today’s article will focus on Tailwind hitting their first major version which has been almost two years in the making.

Even before hitting v1, Tailwind has been adopted by companies like Mozilla and Algolia which shows that it’s not just a gimmick and rather something to stand the test of time.

So, now that we are all caught up, let’s talk about what’s new.

New home page with an awesome animation

The new home page does a better job at explaining what Tailwind is and how people can get started. One of the biggest hurdles when starting with Tailwind is the the mental shift away from pre-defined components like Bootstrap to utility classes. The new navigation and home page animation do a good job at explaining.

No need to create a config file

The configuration file for previous versions used to be a huge blob of configuration options, a default design system. It can actually be a little off-putting. But, with this current iteration, it’s completely optional and only accepts your customization as they come.

New Order Utilities

In the example above, the div with the class order-last will appear at the end of the list — Same behavior to expect from flexbox’s order CSS property. By default, it has a first, last and none suffix which moves an item to the first, last, and normal positions respectively.

It also supports a 12 column grid, which you can extend to fit your project’s requirement.

Quick Upgrade Guide

The first thing you need to do is update Tailwind. Run yarn add -D tailwindcss. If you use npm, run npm install tailwindcss --save-dev.

Then, follow the steps below or head over to the upgrade guide for an in-depth analysis:

Rename tailwind.js to tailwind.config.js or you could delete it entirely from your project.

Replace @tailwind preflight to @tailwind base.

Replace the config() helper with theme() and don’t forget it uses dot-notation to access the properties.

Conclusion

Tailwind is now stable, has an easy configurable interface, and it’s a delight to use. If you haven’t tried it out before, go give it a shot.

]]>Samuel Oloruntoba2019-05-20 08:00:28https://scotch.io/bar-talk/css-scan-the-fastest-way-to-inspect-and-copy-css
https://scotch.io/bar-talk/css-scan-the-fastest-way-to-inspect-and-copy-cssCSS Scan is a super cool tool I've just learned about from Chris Nwamba. It allows you to inspect and copy CSS. CSS Scan is a super cool tool I've just learned about from Chris Nwamba. It allows you to inspect and copy CSS.

It's definitely the fastest way I've seen to copy CSS from a website.

You no longer have to open up DevTools and inspect element to see what styles are.

Quick Usage

Click and you've got those styles in your clipboard ready for pasting:

It is a paid tool, but it's a 1-time lifetime payment. I'm all for supporting developers that make cool stuff so I'm on board. The website has a free demo you can check out: getcssscan.com.

Keyboard Shortcuts

The Chrome extension is convenient and allows us to use a quick shortcut to start the extension:

# windows
ctrl + shift + s
# mac
cmd + shift + s

Get CSS Scan and start copying CSS!

]]>Chris Sevilleja2019-05-17 12:15:57https://scotch.io/starters/react/adding-sass-to-create-react-app-applications
https://scotch.io/starters/react/adding-sass-to-create-react-app-applicationsAdding Sass is one of the first things most developers do when starting an application. Writing in plain CSS can be done, but Sas...]]>Adding Sass is one of the first things most developers do when starting an application. Writing in plain CSS can be done, but Sass provides much more power with features like:

Renaming .css to .scss

Import the .scss File

In our App.js file, we can import the Sass file using the .scss extension.

import './App.scss';

Once we restart our yarn start command, we can see that our Sass file is imported!

Conclusion

Create React App allows us to extend it with a quick command!

]]>Chris Sevilleja2019-05-17 11:44:28https://scotch.io/bar-talk/google-fonts-now-supports-font-display
https://scotch.io/bar-talk/google-fonts-now-supports-font-displayfont-display is a CSS feature that allows us to control how we load fonts.

Google Fon...]]>

font-display is a CSS feature that allows us to control how we load fonts.

Google Fonts are used by many websites (including Scotch.io) and up until now, we didn't have the ability to control how we loaded the fonts.

Now we can add a font-display through a url parameter!

Shipped! @GoogleFonts now let's you control web font loading using `font-display`. Say hello to the `display` parameter 🎉

## How do I use font-display with Google Fonts?
We just have to add a url parameter **&display=** to our Google Fonts url:
```markup
https://fonts.googleapis.com/css?family=Calligraffitti
https://fonts.googleapis.com/css?family=Calligraffitti&display=fallback
```
## Why is font-display important?
Google takes performance into account when it ranks your sites. One of the things that it figures into the performance rating is: **Ensure text remains visible during webfont load**.
This is running a Lighthouse Audit \(found in Chrome Dev Tools\) **without any font-display set**.
![](https://scotch-res.cloudinary.com/image/upload/v1558033858/gjwuejhzdyz4iaozb0lz.png)
Google Audits will penalize a site that doesn't show text to slow network users. By using font-display, users on slow connections can see the text of your site and then get the fancy webfont version after it loads \(with swap or fallback\).
## What are the types of font-display?
The types of font-display are:
* **font-display: block**: flash of invisible text until the font loads
* **font-display: swap**: fallback font until custom font loads \(flash of unstyled text\)
* **font-display: fallback**: between block and swap. invisible text for a short time
* **font-display: optional**: like fallback, but browser can decide to not use custom font
For a more thorough look at font-display, [Monica Dinculescu](https://twitter.com/notwaldorf) wrote up a fantastic post \([font-display.glitch.me/](https://font-display.glitch.me/)\) to visualize the different:
![](https://scotch-res.cloudinary.com/video/upload/f_auto,fl_animated/v1558033882/a5crz4rlrvqmfivzfbbi.mp4)
## Go Forth and Use font-display!
It's a quick change to add font-display updates to your sites. After making the changes, we've seen some people get some nice performance boosts!

]]>Chris Sevilleja2019-05-16 12:11:54https://scotch.io/starters/react/using-create-react-app-to-make-react-applications
https://scotch.io/starters/react/using-create-react-app-to-make-react-applicationsUsually when you create a React application, you’ll be creating a single page app (SPA). In order to make setting up single page apps easier, a CLI tool called create-react-app was made.

I personally use the npx way since that's what's familiar to me and I've been using first.

Starting a new React project

We’ll use npx to create a new project:

npx create-react-app super-duper-app

This is the new folder structure we’ll see:

Let's explore what we can do with our new application.

Starting our React App

To start developing on our React app, we can tell the CLI to run everything and open our app in the browser at http://localhost:3000.

# with npm
npm run start
# with yarn
yarn start

The start command will run webpack and Babel and get our app loaded.

Essentially what this command does is compile all of our React code including transpiling, checking for errors, compiling Sass, creating a JavaScript bundle of all our code, injecting this into the public/index.html file and finally loading it all up in our browser.

What do we get by default?

Create React App comes with many things out of the box including a starting point for every React application.

A Build Setup

Our React applications need a build step to transpile our ES6 code to something that all browsers can read. This is why you will see many setups that don't use Create React App will set up webpack and Babel.

Create React App comes configured with webpack and Babel so you don't have to set it all up.

public/ folder: Everything in the public folder will be the things that are available to browsers. We won't be working in here too often. This is just the assets that we will bundle with our application with minimal work.

src/ folder: This is where we'll do the majority of our work. All of our React components will live inside the src/ folder.

root folder: This is where our configuration files are located. Most of our configuration lives in package.json

Build Scripts

Create React App comes with a few scripts that are helpful for our development. We will use these scripts whenever we want to:

# starting our app for development
npm start
npm run start
yarn start
# building our app for production
npm run production
yarn production
# testing our application
npm run test
# ejecting our application (ONLY DO IF YOU KNOW WHAT YOURE DOING)
npm run eject

start: This command will start our application for development. It will even open up our application for development in browser at http://localhost:3000.

build: We can bundle our application for production and generate only a few files that we can host for our users.

test: This will run all of our tests like the one that comes with Create React App in App.test.js

eject: Ejecting will give you access to configure every aspect of your React application. This means that Create React App is no longer handling the configuration for your application. This command is only for those that are 100% sure they want to leave the comfort of CRA and need extra configuration.

Ability to Run Tests

Here's a quick look at what running tests looks like with npm run test:

Bundling for Production

In order to host our application for users to use, we need to bundle all of our code into a few JavaScript files that our users can load. Create React App comes with a convenient script

We can run the following and see a few build files get created.

# bundle this app for production
npm run build

Notice the new files that are created. This is all we need to provide our React app to our users!

We can then see our new files in a newly created build folder. This is what we will host on a server and point users towards our index.html file. React will take care of the rest.

We'll talk more on what bundling for production means in a following post.

Conclusion

Create React App is an awesome tool for React developers. We used to have to configure our own webpack and Babel setups in the past.

Now, React developers can get straight to developing awesome React apps. They no longer have to worry about setup.

Use Create React App to start your applications. It provides a solid base and keeps getting updated by the React team.

]]>
Chris Sevilleja2019-05-15 11:56:00https://scotch.io/courses/10-react-challenges-beginner/show-an-alert-based-on-an-input
https://scotch.io/courses/10-react-challenges-beginner/show-an-alert-based-on-an-inputEvents make the core of interactivity in JavaScript, from listening to form inputs, scroll events to button clicks. The knowledge of handling events in JavaScript is essential.

CodeP...]]>

Events make the core of interactivity in JavaScript, from listening to form inputs, scroll events to button clicks. The knowledge of handling events in JavaScript is essential.

Hint

Solution: Show Alert when Typing

Todo: Video here.

Controlled components in React have their value determined by a state variable. Also, these components are used to set the value of an assigned state variable.

The <input> element is one such element, and it receives its value from data saved in state, and it is used to change the value of this same data in state, thereby making the state variable the single source of truth.

This challenge is solved in 3 steps:

Store the input data in state.

Handle input to the form.

Show an alert on a specific input.

Store form data in State.

The data from the input element needs to be stored somewhere so it is used in the component. This data is saved in state. Import the useState react hook into the component with:

import React, { useState } from 'react';

Create a new state variable phrase in the component with an empty string as default.

]]>Chris Sevilleja2019-05-10 13:57:16https://scotch.io/courses/10-react-challenges-beginner/use-react-state-to-update-the-dom
https://scotch.io/courses/10-react-challenges-beginner/use-react-state-to-update-the-domA common theme in modern front-end JavaScript libraries/frameworks is that they can help you manage the data in your applications.

Once you update something, React can immediate...]]>

A common theme in modern front-end JavaScript libraries/frameworks is that they can help you manage the data in your applications.

Solution: Update Data from an Input

TODO: Video Here

With state in React, various parts of an application can be updated with data from other parts. In React 16.8, Hooks was introduced, which provided a way to use features of React class component features in functional components.

State provides a way to create and update dynamic data in an application.

In this challenge, we utilize the useState() hook to create and update state variables.

This challenge is completed in three steps:

Create state variables with default data

Pass the variables to the page

Create a form to handle the updating of the state data

Create State Variables

For this challenge, you require two state variables to hold name and age. Create them using the useState() hook in the App() component with:

Here, we created two variables name and age then assigned them default values of Chuloo and 38 respectively. The setName and setAge methods, update the state data when called and passed a new data value as a parameter.

Pass the Variables to the Page

In the returned JSX with a class of input-display we shall display the value of the state variables. Do this with:

We currently have the data from state displayed. The default values are on display until we alter them.

Handle Update of the State data

<input> elements in React are "controlled components" in that the value of the input is determined and updated using state. With this in mind, we shall update the value of the input to be that of its corresponding state data.

Also, when the value of the input element changes, its corresponding state data updates. This makes the state variable the single source of truth, as it controls the input element and its value.

Assign the name input's value and handle any change using the onChange attribute in App() with:

]]>Chris Sevilleja2019-05-10 13:56:38https://scotch.io/courses/10-react-challenges-beginner/loop-over-and-display-data-with-jsx
https://scotch.io/courses/10-react-challenges-beginner/loop-over-and-display-data-with-jsxData comes in all shapes and sizes. In JavaScript, an array is how we hold sets of data. For the majority of our site content, we use an array of objects.

Looping through and sh...]]>

Data comes in all shapes and sizes. In JavaScript, an array is how we hold sets of data. For the majority of our site content, we use an array of objects.

Looping through and showing data from an array is an essential skill.

In this React challenge, we'll loop through array data and display information from each item.

The Challenge: Loop Over an Array

For this challenge, you have an array of users. Loop over those users using JavaScript's .map().

Loop Over the Array

.map() in JavaScript iterates through an array and calls a specified function for each of the items. Components in JSX are JS functions. For each object in the array, a block of JSX elements is returned.

Also, data from the object is passed to each block using the JSX handlebars-like curly brackets.

In the App() component of src/index.js iterate over the imported data using .map() with:

Do you notice the key attribute? React requires a unique identifier for each element in the array. This key attribute could be a unique ID, or something unique to each object. Here, we use the index position of each object (that's unique too!).

Conclusion

In this challenge, we built out a page using data from a provided array of objects. Iterating through provided data is a necessary process when building out rich, data-centric user interfaces in React.

]]>Chris Sevilleja2019-05-10 13:56:14https://scotch.io/courses/10-react-challenges-beginner/display-simple-data-with-jsx
https://scotch.io/courses/10-react-challenges-beginner/display-simple-data-with-jsxOne of the building blocks of React is the ability to use HTML elements when developing components.

JSX allows us to write simple markup in HT...]]>

One of the building blocks of React is the ability to use HTML elements when developing components.

JSX allows us to write simple markup in HTML. JSX is often looked at as a difficult thing to learn in React, but it's worth looking into since JSX is really just JavaScript.

Learning JSX will make you a better JavaScript developer.

In this React challenge, we will take data and display it using JSX.

The Challenge: Display Data using JSX

In this challenge, we will give you user data and you have to display it using JSX. The main tasks are:

Show data

Bind data to an HTML attribute <img src=

Create a link to the user's Twitter profile: https://twitter.com/chrisoncode

Bonus Points

Solution: Display Data in JSX

TODO: Video Here

JSX affords us the ability to write components using HTML-like syntax in React. To pass data into JSX elements, we use handlebars-like curly brackets {...}. These curly brackets let the JSX know to treat it as JavaScript.

JSX will evaluate anything within the curly {} brackets as JavaScript.

With this, we can pass variables, functions, evaluate expressions e.t.c. right in the component.

Now, we have the data being displayed. We have bound the user's avatar to the <img src and have also added the alt attribute on the img tag.

To show a user's name, we will use our JSX curly brackets: {user.name}

Linking to the User's Twitter

We've been able to display data and also bind to an HTML attribute (src). Next, we need to create a link to the user's Twitter. We have their Twitter username (chrisoncode). To create the Twitter link, we can do the following:

]]>Chris Sevilleja2019-05-10 13:53:14https://scotch.io/tutorials/new-ecmascript-modules-in-node-v12
https://scotch.io/tutorials/new-ecmascript-modules-in-node-v12If you’re familiar with popular JavaScript frontend frameworks like React, Angular, etc, then the concept of ECMAScript won’t be entirely new to you. ES Modules have the import and If you’re familiar with popular JavaScript frontend frameworks like React, Angular, etc, then the concept of ECMAScript won’t be entirely new to you. ES Modules have the import and export syntax we see often in frontend frameworks. Node uses CommonJS which relies on require() for imports.

We can now use import and export in Node in addition to require().

That’s not all that comes with the new Node v12 release, let’s talk about all the new cool features we can expect.

New features in Node v12

New ES Modules

Before now, a previous Node release shipped with experimental support for ECMAScript modules. This support was behind the --experimental-modules **flag and still is, but a lot has happened since the last release and we are happy for what is coming next. We know for a fact that some of the concerns and feedbacks raised from the last release has been acted on and is coming to life in the next release.

The outstanding feedback being that Node.js needs to provide a way to use import and export syntax in *.js* files. In the new --experimental-modules, two ways will be provided for you to be able to do this:

Set “type” : “module” inpackage.json

// package.json
{
"type": "module"
}

This tells Node.js to treat all .js files in your project as ES Modules. If you still have CommonJS files that you would not like to treat as modules, you can rename them with the .cjs file extension, which will tell Node.js to parse them as CommonJS explicitly. Alternatively, you can put all your CommonJS files in a subfolder containing a package.json file with "type":"commonjs", under which all .js files are treated as CommonJS.

Note, If the nearest parent package.json file lacks a "type" field, or contains "type": "commonjs", extensionless and .js files are treated as CommonJS. If the volume root is reached and no package.json is found, Node.js defers to the default, a package.json with no "type" field.import statements of .js and extensionless files are treated as ES modules if the nearest parent package.json contains "type": "module".

You can think of this type and extension scoping as the way CSS order of precedence works, it cascades down the tree from the child all the way up to the parent.

The second way of using the import and export syntax is to use --input-type=module to run string input (via --eval, --print or STDIN) as an ES module. The --input-type flag can be either --input-type=module or --input-type=commonjs. In our case, it’ll be the earlier since we are setting it to modules, not CommonJS.

More expected WIP features

Given that the Node.js Modules team are still working on these features, we can’t exactly report them as existing features. Why? they are still being worked on so they are all probably still going to change, however, we have an idea of what they are and how they are likely to behave.

Module Loaders

The Very WIP feature. Though the first implementation of the --loader API has shipped, it's still being worked on hence, it is still subject to changes **in the next release.

Package path maps

This feature has not shipped yet. It would redefine how we make module imports and allow for less verbose imports in certain situations.

Automatic entry point module type detection

This feature will make it possible for Node to identify the type of module we have present in our projects. When shipped, it will be possible for Node to know if a particular module is an ES Module or a CommonJS Module.

There are so many other awesome features in Node v12, feel free to dig deeper and get a piece of the awesomeness in the official blog post by the Modules Team on Medium. But in the meantime, let’s take a closer look at the types of modules we have in Node.

Different Types of Modules in Node

This might look very obvious at this point but i have come to understand with experience that most people have troubles understanding the different types of modules we have in Node. Given that until recently, all we needed in Node is the CommonJS syntax, it’s understandable that a few people find it confusing.

There are basically two module types in Node.

The CommonJS Module type and

The ES Module type

CommonJS Module

The CommonJS Module is the default module that comes with Node. Before the inception of the ES Modules, every Node application works with the CommonJS module construct that uses the require() and module.exports syntax to pull in modules and export them. Consider this example:

Here, we just imported a products module into our main.js file from a different file in our app’s src directory. We can go ahead and use the module in the current file as we please. How is this possible? Because the products function is set to the exports object in the src/products file according to CommonJS specification.

The Node.js implementation is not so different from what we’ve just seen above from CommonJS. The difference is in the way the modules are exported from their host files. While CommonJS exports modules with the exports variable, Node modules uses module.exports object.

Just like the CommonJS implementation, this is equally a synchronous process as the files are loaded one after the other in the order they appear inside the file.

ES Modules

ES Modules can be considered an improvement on the CommonJS module system. It offers possibilities for importing and exporting modules just by using the import and export keywords as a replacement for require in CommonJS. Unlike CommonJS, the ES Modules are compatible with both synchronous and asynchronous modes of operation.

Considering the products example we saw with CommonJS on the previous examples above, we can redo the file with ES Modules like so:

//src/main.js
import products from 'src/products'

As we explained before, the import statement is used to bring modules into the namespace. It operates almost exactly as the require alternative in CommonJS but it is not dynamic, hence, you cannot use it anywhere in the file. Again, we were able to import this file for use here because it has probably been exported from it’s host file.

The export statement here makes it possible for you to access this function from another file. Simply put, it makes the function widely accessible. As a result of this, static analyzers will first build the tree of dependencies while bundling the file before eventually running code. This is in my opinion a major advantage of using ES Modules.

ESM in Node in the past

The concept of ES Modules in Node is not exactly new, it’s been available since 2017 when Node.js 8.9.0 shipped experimental support for ECMAScript modules, known for their import and export statements behind the --experimental-modules flag.

However, up until this moment, this feature has remained in the experimental state. Reason? to allow the Node.js community the time to use it and provide actionable feedback on that design. Since then, a lot has happened. Major browsers now support ECMAScript modules (ES modules) via *<script type=*``"``*module*``"``*>*. Npm packages with ES module sources are now available for use in browsers via *<script type=*``"``*module*``"``*>*. Support for import maps, which bring to browsers Node.js-style package names in import statements, is coming to Chrome. And a lot more other things.

Having waited for a long time, received feedback on the experimental ESM design and owing to the fact that there are other runtimes and environments where ES modules are in use, there’s no better time for Node.js to support this ESM JavaScript standard than now. And this is why the Modules Team has announced a new implementation for supporting ES modules. According to them, it will ship as part of Node.js 12 and will replace the old *--experimental-modules* implementation, behind the same flag.

Get started with v12 using nvm

While we wait for a long term support for ESM, we can start getting familiar with its operations and features using nvm. What is nvm? nvm lets you install multiple versions of node on one machine and switch between them when you need to.

What this means is that, even though you’re currently running Node v6 or v10 whatever version, you can switch up to the latest version or an older version and try out things while still keeping your current version and files intact.

I would love to cover how you can go about installing nvm, and using it to manage your Node versions to try out different features that don’t yet exist in your current version but Michael Wanyoike has already done a great job at it on this post on Sitepoint. If you will be interested in learning how nvm works on different OSS platforms, give the post a visit.

Use —experimental-modules flag to support imports until LTS

Like we mentioned earlier on in this post, ES Modules has been around for a while and there are basically two intuitive ways we can go about using them until LTS.

node index.js --experimental-modules

node --experimental-modules index.js

Unfortunately the first way i.e using the node index.js --experimental-modules does not work, hence, to support ESM imports in your Node applications, you will have to use the second option above.

Dynamic imports is going nowhere

It is worthy to note that dynamic imports are not under any threat from the incoming ES Modules implementation. Prior to this ESM era, dynamic imports provided us with the ability to dynamically import and use modules from different locations in our application.

Given that dynamic imports returns a promise for the module namespace object of the requested module, it's possible to use async/await and the .then()-based callback style to handle all module behaviours which makes it possible to load modules asynchronously. This is why we all love it and it’s just a good news to know that we won’t lose it to the new implementations.

What about importing JSON files?

For now, importing JSON modules are not supported out of the box yet in the module mode. It is however, supported in the commonjs mode and are loader with the CJS loader. That said, efforts are currently being made to ensure that JSON imports are supported in the module mode. For instance, at the moment, WHATWG JSON modules are currently being standardized, and are experimentally supported by including the additional flag --experimental-json-modules when running Node.js.

Even though JSON imports are supported out of the box in commonjs mode, when the --experimental-json-modules flag is included, both the commonjs and module mode will use the new experimental JSON loader.

There’s a bit of a drawback though, the imported JSON only exposes a default, so right now there is no support for named exports. Since the experimental JSON loader takes precedence over the commonjs mode too, a separate cache entry is created in the CommonJS cache, to avoid duplication. The same object will be returned in CommonJS if the JSON module has already been imported from the same path. Consider the example below:

The earlier will fail because of the unavailability of the --experimental-json-modules.

Final thoughts

There’s been so much talk around the new EcmaScript Modules coming to Node.js v12. In this post we took a closer look at it to understand what it offers as compared to the usual CommonJS alternative.

]]>Chris Nwamba2019-05-09 09:00:42https://scotch.io/tutorials/create-a-bouncing-page-loader-with-css3-animations
https://scotch.io/tutorials/create-a-bouncing-page-loader-with-css3-animationsSide projects are not only fun but they bring a whole lot of learning experience for you. While hunting for a pre-built page loader for a website I ended up coding one for myself.

Initially,...]]>

Side projects are not only fun but they bring a whole lot of learning experience for you. While hunting for a pre-built page loader for a website I ended up coding one for myself.

Initially, I had a view that implementing CSS3 animations are quite a cumbersome task so, I looked for an online service for creating simple animations. However, I didn't find a reasonable page loading CSS animations which met my project's requirements. I wanted something neat and simple.

After toying around with the code in less than an hour I managed to build a simple implementation of a bouncing page loading experience with CSS3 animation keyframes which I am super excited to share with you.

Project Research

I didn't jump to CSS @keyframes at-rule right away. It took me some time and research to figure out an effective way to code a page loading experience. Initially, I started playing with the CSS Transitions which help you change CSS property values, over a range of time. But I wanted to keep the process as simple as it can get and the @keyframes at-rule served me best.

Project Setup

Here's what we’ll be making by the end of this tutorial:

HTML

I added a div with the class called loader. This div is responsible for creating all the page loader elements. Inside this div, I added three consecutive span elements each representing a page loader circle.

Each loader circle has width: 1rem; and height:1rem; with #FFB651 color. By default, the shape of my page loader in square. To give it a circular shape I set the border-radius to 50%. Just uploading a GIF to show how the loader looks like without the border-radius property.

I also added bit of a margin between the circles but the most interesting part here is the animation property. We are using an animation keyframe called bouncingLoader that runs once in 0.6s and repeats itself inifintely. Let's talk more on that and the animation delay properties below.

So, here's a quick tip i.e., if you want your loader to be in square shape don't use the border-radius property.

Creating Animation Keyframe

Keyframes are used to define the animation behavior and give us complete control of one cycle of a CSS animation. We define it as @keyframes at-rule followed by the name of the animation which is bouncingLoader in this case.

Inside a @keyframe rule, you use the keywords from and to in order to specify a starting and ending point for your animation. Equivalently, you can also use 0% for from which depicts the starting point and 100% for to depicting the ending point of your animation.

Moreover, if you want several animation transitions, you can define a range of percentages each containing a list of styling selectors. These percentages can be listed in any order and with any difference between them. A simple representation of these percentages is shown below:

I am using the keywords from and to which define the basic styling properties of width, height, and opacity of the circles. Other than that, to create the bouncing effect, I used the CSS transform property to change the coordinates of a given element hence transforming the location of each circle.

With this transform property, I've used the translate3D() function which takes threeinputs explaining the change in (x, y, z) coordinates. Since I wanted my loader to run in a wave motion, I need to translate primarily along the y-axis keeping the x and z-axis constant. Thus, my ending point value is (0, -1rem, 0).

Let me show you a little demo how to play with this property. If I set my ending point value as transform: translate3d(1rem, 0rem, 1rem);. It'll mean that I am transforming it along the x and z-axis while keeping my y-axis constant. Now my animation will look something like this:

Using Animation Delay with Keyframe

Now begins the final part. Since I have written the code for my @keyframe, it’s time to set it up and running. The kind of animation which you are viewing in the GIFs above was made possible with the following few lines of code:

animation-name: Defines the name of your animation which is loader in my case.

animation-duration: Configures the length of time which your animation will take to complete one cycle.

animation-iteration-count: Tells how many times you want your animation cycle to play before it stops.

animation-direction: Defines that in which direction is your animation going to play.

Apart from these there are several other sub-properties as well. You can browse them from here.

Based on these I have defined my animation as follows:

animation: bouncingLoader 0.6s infinite alternate;

This line of code does the following three things:

☑️ Tells the loader element to use our keyframe bouncingLoader.

☑️ It also sets the length of the animation to 0.6 seconds.

☑️ It runs the animation an infinite number of times.

☑️ Upon completion of one single cycle, the animation direction alternates i.e., it reverses.

I have defined these properties for the first circle of my bouncing loader. To target the second (2) and the third (3) circle, I've used the nth-child(n) selector which allows you to select and target one or more elements which are the nth-child of its parent. Moreover, for the remaining span elements, I have just defined the animation-delay, so that each element does not start to animate at the same time.

Your turn

After developing this animation, I have realized that CSS is amazingly powerful. There are several ways of creating animations like this. I'd love you hear your suggestions and the way you create CSS animations.

Thanks for reading! If this tutorial was helpful and has piqued your interest, try it out yourself and share your feedback in the comments section below.

]]>Maedah Batool2019-05-07 11:00:23https://scotch.io/bar-talk/10-awesome-things-from-ms-build-day-1
https://scotch.io/bar-talk/10-awesome-things-from-ms-build-day-1Microsoft Build is packed with gazillion announcements, fun activities, people and it's so much to fit into one article. I won't be doing justice to the event by trying to fit everything that happe...]]>Microsoft Build is packed with gazillion announcements, fun activities, people and it's so much to fit into one article. I won't be doing justice to the event by trying to fit everything that happened today in one article but I am just going to try and highlight some exciting news for those who are not able to catch up.

Keynote by Satya

The most exciting session was the keynote where Satya and few crew announced a handful of exciting features and products.

Satya spent approximately 2 hours on stage just making announcements — I couldn't even catch up with all the exciting news. Most times I got lost dwelling in exciting as a result the previous announcement he made and I missed the next. That was how packed it was.

I am going to do my best to talk about few of the announcements I caught and you can always learn more when the videos are released.

Edge Everywhere

Edge is now cross-platform. Yes, the browser can now be downloaded on iOS and Android devices. With Edge being Chromium based, building experiences for users and developers is going to become easier and more streamlined.

Better devtools, easier ad handling, super performant browser, cross-platform, etc. These are just few of what I was able to catch and trust me there are more powerful features on Edge today.

Windows Terminal and WSL2

Windows is getting a new terminal dubbed "Windows Terminal". It will be able to work with cmd, PowerShell, and Windows Subsystem for Linux.

React Native on Windows

Your customers are windows users but your developers love JavaScript, right? Well, you can now write React Native and build for not only iOS or Android, but also on Windows computers. I was privileged to help out on a booth with one of the developers working on this. She showed off demoes and compiled a React Native app to Windows right in front of us.

You don't have to worry about UI consistency because there's a library with a all the windows theme that helps you stay on track with what your users are used to.

Fluent Design System

Microsoft has published a new site on their design ideology called Fluent. Check out the new site:

Fluid Framework for Content Collaboration

We are building a framework for content collaboration. Yes, framework. I am a content junkie — I write a lot of technical articles, edit a lot, share with editors, publish, etc. But how accessible is my content to other collaborators and consumers?

Fluid framework is a realtime framework that integrates with any type of content platform you are maintaining or building. Fluid empowers you with tools like realtime collaboration, multiple realtime collaborators, realtime language translations, etc.

My favorite feature about Fluid is how I can write my content in English and have Spanish, Chinese and French contributors on it. This is some next level content platform.

Smarter Assistance Research

As an African, I have a deep outstanding accent. Sometimes when I speak with my friends they try to teach me the correct pronunciation to a word. My response to this is usually "that is the African way to pronounce it".

Well, my friends wouldn't agree with that but the personal assistance (Cortana) we are building at Microsoft totally does. The AI is actively adjusting to understand how you say words. It is conversational, more interactive and confirms your commands but asking you further questions. This is personal to me because I have tried a lot of personal assistance and find myself repeating myself. This is what it means to build for the next billion users.

Jargon-Sensitive Speech Service

Still on voice based artificial intelligence, you can now have a trained service that understand the jargons in your speech. This is useful for medical, tech, and legal organizations. This video does the best justice to this feature:

Powerful Mixed Realities

I have never considered mixed realities until today. At this point I want to sign up to whatever it takes to build interactive realities. The opportunities presented by mixed realities is endless — from interactive learning in schools to accessibility for the next billion users. Imagine having a conference where the speaker can interact live with the audience on stage without being physically there.

Here is a short video I managed to catch on this:

Azure and Code

Azure and VS Code got a lot of announcements that I can't go into detail about so it doesn't bloat this article. That said, here are some of the exciting news under these categories:

Visual Studio and VS Code live share just got better

You can now connect VS Code to a deployed projects and make live changes

We will soon be able to sign-up/login to Azure with Github

New windows CLI that supports Powershell, cmd and WSL all in one

Visual Studio Online

Booths

We wanted to teach developers and also collect feedback. Booths were are the heart of the event. You can walk in and ask the creator of TypeScript a "why" or "how" question. You could bring what you are working on and we live code together. You can just come by for stickers, shirts, swags, if that's all you care about.

The booths were staffed by core engineers and developer advocates. Helping everyone with all their questions. It is super fun and sometimes gets weird cause someone would ask a question like "why Vue and not Angular?".

Here are some pictures developers hacking or interacting at the booths:

People Behind Features and Products

I am big on know the people behind a product or feature. The more I can build a connection with them, how they thing, what they think of, etc, the more I can understand the reasons behind these products and features.

Channel 9 team was live-interviewing engineers, advocates, managers, directors, etc regarding some of the annoucements today.

]]>Chris Nwamba2019-05-07 07:00:04https://scotch.io/bar-talk/microsoft-announces-a-new-windows-terminal
https://scotch.io/bar-talk/microsoft-announces-a-new-windows-terminalI am a big fan of Windows (shame shame shame). I’m usually the only Surface in a sea of MacBooks. I love both platforms and work on both. My kitchen laptop is a 2015 MacBook and I’...]]>I am a big fan of Windows (shame shame shame). I’m usually the only Surface in a sea of MacBooks. I love both platforms and work on both. My kitchen laptop is a 2015 MacBook and I’d gladly get another if they ever fix the keyboard so that it has more than 1mm of travel.

Recently, Windows brought Bash to Windows. I now use the Windows Subsystem for Linux (WSL) for all my dev work. The new Windows Terminal will make the dev experience with the command line, PowerShell, or the WSL much easier.

A New Terminal!

At Microsoft Build, a new terminal was announced! It can wrap the old school cmd.exe, PowerShell, or the new wsl.exe.

Features

The cool things about the new terminal

Graphics enhanced (GPU)

Tab support

Emoji support

Can be used with CMD, PowerShell, and WSL

Coming in June

I currently use Hyper as my terminal and have that wrap around the WSL. It’s been working great and I love having an extra option.

It’ll launch mid-June along with WSL 2 and is a solid win for developers working on Windows. Microsoft has done some solid work for the open source and developer community recently and I can’t wait to see what else is in store.

]]>Chris Sevilleja2019-05-06 11:11:18https://scotch.io/starters/react/the-ways-to-use-react
https://scotch.io/starters/react/the-ways-to-use-reactBefore we can jump into learning more about the specifics of React, it's important to talk about all the ways we can use React.

This will give us a good mental overview to see how React can ...]]>

Before we can jump into learning more about the specifics of React, it's important to talk about all the ways we can use React.

This will give us a good mental overview to see how React can be added to any project. In a nutshell, it comes down to the following:

React can be used by:

Adding React to an existing site

Using React to create a fully single page app

Let's talk about the difference between an existing site and single page apps (SPA). React is a great fit for both scenarios. It's ability to scale based on the project, small or large, is one of the main reasons React is loved by so many.

Adding React to an Existing Site

If you've already got a website and want to add React, it's a two-step process. Usually you'll have a website that's served with a server-side language (PHP, Ruby, Node). This means the view is generated by your server and an HTML file with content like paragraphs, headers, titles will be served to your user.

This is how the Scotch.io site is made. It is generated by PHP/Laravel and we serve HTML/CSS to users. After we serve the page, we then add React to parts of the site like the top navbar, search sections, and a few other things.

Here's a look at what this could look like:

To add React to an existing site, the process is:

Add the React and ReactDOM libraries

Use Babel to make sure browsers can understand our React code.

The first step is the quick part. The second step is where it can get tricky based on the project you have.

There are many variations to how websites are built so you'll need to look at your current site and see if you already have a build system (ie Gulp, webpack, or something similar).

Scotch.io itself is a website that is served by Laravel and we add React on top using webpack via Laravel Mix.

What does this look like in code?

We would have our website served via a server-side language and then attach JavaScript on top. Here's some code to demonstrate our HTML page.

We are serving a full HTML page to our users and notice that we have a div that we have labeled with an id of react-component-here. We can then add in our JavaScript (that is bundled with webpack and Babel). That code could look like so:

Now React has taken over that one specific area of our site. If you look at the Scotch.io source code, you'll see that we have a few divs that take this same approach. <div id="react-search-bar"></div> is the one that handles our header search bar.

In addition to adding React onto an existing site, we can use React to build out the entire site. This is called a single page app.

Single Page Apps

Single page applications are apps that are built completely with JavaScript. The main difference between SPAs and applications that are served from a server is routing. For a server-served site (like Scotch.io), you'll see a refresh for every page you click to. That's because the browser has to get new content from the server.

For Single Page Apps, you won't see a refresh as the JavaScript (React in this case) will be responsible for grabbing new data and displaying it to you. Routing is handled via JavaScript all in your browser without a page refresh.

Popular single page apps are:

Facebook

Medium

Twitter

Instagram

Uber

Airbnb

Single page apps are the focus for this starter course as SPAs are becoming increasingly popular in web development.

Benefits of React Single Page Apps

The big benefits of single page apps are that they offer a better user experience. They offer immediate feedback to users.

Routing is fast and doesn't require a page refresh

Interactions happen quickly (real-time)

Offline and app-like behavior can be added

Incredibly fast. Able to be served globally and statically

Of course both of the above benefits could be added to server-rendered applications. It is just a quicker process if all of the application is built on the client-side instead of having a site that is server-side + client-side.

What does this look like?

We are still serving an HTML file to our users, but in this case it is very minimal. It will look something like this:

Notice that we only have one div named app. The entire React app is injected here and takes up the entire page. Contrary to our above example for server-rendered applications, we have all our logic happening inside of our app.js instead of partly in HTML and partly in JS.

Conclusion

We'll be focusing on the single page app way. In the upcoming examples, we'll work with some tools to make React development easier and also create-react-app, a tool that Facebook released to make generating React single page apps very easy.

]]>Chris Sevilleja2019-04-22 10:29:06https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/range-sum
https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/range-sumSometimes, while performing mathematical calculations, there comes the need to sum up a range of numbers. Some programming languages make this easy by implementing helper functions that enable one ...]]>Sometimes, while performing mathematical calculations, there comes the need to sum up a range of numbers. Some programming languages make this easy by implementing helper functions that enable one achieve such tasks simply via a function call. Not JavaScript!

In this challenge, we implement our own helper function for summing up numbers within a specified range. The range is specified using an array in the format:

[minimum,maximum]

You should already have your development environment setup for this course. Open the cloned repository and inside the Beginner folder, navigate to the rangeSum folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

The Challenge

Given an array of two numbers, return the cummulative sum of the two numbers and all the numbers between them. E.g

rangeSum([1,9])
// Should return 45 i.e 1+2+3+4+5+6+7+8+9

Algorithmic Thinking

We are to write a function that accepts one parameter i.e an array containing the minimum and maximum limit of the range respectively.

To solve this challenge, we need to sum up all the numbers as we loop through all the numbers starting from the minimum until we arrive at the maximum limit.

Pretty straightforward! Let’s do this!

Code Implementation

Let's now consider four ways to solve this challenge. They are:

Using a For-loop

Using the Arithmetic Progression Formula

Using Recursion

Using .reduce()

Using a For-Loop

In this approach, we use a For-loop to iterate through every value from the minimum arr[0] to the maximum arr[1].

Notice how we initialize an accumulator variable sum to 0 . With sum, we accumulate the sum by adding the current value of the iterator on every iteration. We basically start at the minimum value received and add every number we encounter to our sum until we arrive at the maximum number.
At the end, we return sum as the final result.

Now let's try using a formula.

Using the Arithmetic Progression Formula

In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers ordered such that the difference between the consecutive terms is constant. This simply means, a list of numbers where the difference between each number and the next is always the same. Notice that in a range as shown below, this applies.

1,2,3,4,5,6,7,8,9,...

In the sequence above, the common difference is 1 and this will remain the case no matter how much farther we extend the list.
A general formula for calculating the sum of an arithmetic progression for a certain range of numbers with n number of elements is:

a1 = First term of the sequence
an = Last term of the sequence
n = Number of elements in the sequence

We derive the value of n as maximum limit - minimum limit + 1 as shown in the first bracket within the return statement. The rest of it follows accordingly, thus we arrive at the final sum which we return from the function.

Now let’s try recursion.

Using Recursion

In this solution we apply recursion by continually reducing the maximum limit and summing up all the returned values to arrive at the final sum.

Notice that we first specify a terminating case such that as soon as the maximum and minimum limits are equal, the recursion terminates by returning the current minimum i.e arr[0].

A step by step analysis of what is going on above will reveal that while we continually reduce the value of the maximum limit by 1 for each recursive cycle i.e arr[1] -1, we sum up all the maximum limits up until the minimum limits equals the maximum limit. Thus, for rangeSum([1,9]), we would have:

9+8+7+6+5+4+3+2+1

Let’s consider one final approach.

Using .reduce()

To apply this method, we first need to generate an array containing all the numbers found within the specified range. Thus, we initialize a variable arrList with an empty array for this purpose. Using a for-loop, with our iterator i starting from the minimum value arr[0] we push every value of i into our arrList until we arrive at the maximum limit arr[1].

After successfully populating arrList, we call the .reduce() method on the array. Starting with 0 as the initial value of the accumulator, we add the current number num from the array list to the accumulator and then move on to the next. At the end of this process, the final value arrived at is the sum and is returned as such.

Wheeew!!! That was pretty tasking.

Testing

Testing correctness with Jest

To test the solutions above, run the following command from your terminal:

Testing Performance with JSPerf

Here on JSPerf, we run a performance comparison of the four solutions explored above. The screenshot below reveals the result.

The performance test above reveals that the optimal solution is the Arithmetic Progression Formula. The least optimized solution which is approximately 100% slower is the Recursive Method.

Practical Application

This challenge finds its application in mathematical operations involving number theory and combinatorics. It also suffices as a coding challenge.

Conclusion

We have now considered four(4) ways to sum up numbers within a specified range. We have also successfully identified the optimal solution to be the Arithmetic Progression Formula.
Make sure to explore other ways of solving this challenge. You can always perform a performance comparison using JSPerf as well as share your findings in the comment section.

Further Reading

For more information on the techniques and concepts applied above, you may use the following links:

]]>Philip Obosi2019-04-06 12:48:01https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/integer-reversal
https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/integer-reversalReversing an integer usually comes across as an easy thing to do for most developers. However, on closer evaluation, it gets a little tricky due to certain requirements and constraints involved. Th...]]>Reversing an integer usually comes across as an easy thing to do for most developers. However, on closer evaluation, it gets a little tricky due to certain requirements and constraints involved. This article addresses these by providing a step-by-step explanation of the process behind reversing an integer in JavaScript.

You should already have your development environment setup for this course. Open the cloned repository and inside the Beginner folder, navigate to the IntegerRevesal folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

The Challenge

Given an integer, return an integer that has the reverse ordering of that which was received. E.g

reverseInteger(-123) // should return -321

Keep the following rules in mind:

The signs must not change i.e -123 becomes -321

The value returned must be an integer.

All insignificant zeroes must be removed i.e 900 becomes 9 and not 009

Algorithmic Thinking

To solve this challenge, we are expected to write a function which accepts the number to be reversed and returns the reversed number as the result.

There is no way to directly reverse an integer in JavaScript without some clever manipulation or computation. Earlier, we learned how to reverse a string and we even went further to determine the optimal approach. This will come in handy for this challenge.

Theoretically, we can reverse an integer by applying the following steps:

Applying this in solving this challenge,we shorten the steps to be followed from what we have above into 4 steps:

Convert the integer to a string

Reverse the string

Convert back to an integer

Return the reversed integer with a corresponding sign as the received.

We shall now follow these steps in coming up with a solution for this challenge as shown below.

Let’s get coding!

Convert the Integer to a String

The .toString() method in JavaScript is used to convert a number to its string equivalent in any number base(radix) between 2 and 36 as specified. If the radix is not specified, the default radix is assumed to be 10.

To convert the integer to a string, we call this method on the received number as shown below:

num.toString()

Applying this step to the challenge sample gives a string "``-123``".

Reverse the String

To reverse the string we’ll apply the optimal method as determined in the “String Reversal” challenge. We simply pass in the converted string as shown below:

This step reverses the string from the previous step, so we have "``321-``".

Convert back to an Integer

To convert back to an integer, we used the parseInt() function to convert the reversed string back into an Integer.

The **parseInt()** function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems) if any.

let reversedNumber = parseInt(reversedString)

When we convert the reversed string above back to an integer, we have 321. Notice that this gets rid of the negative sign at the end. Thus, in the next step we add the corresponding sign to the reversed integer.

Adding the corresponding sign

This is the final step in reversing an integer. Using the Math.sign() function, we are able to determine the sign on the number that was received. With that we can adjust our reversedNumber accordingly.

The **Math.sign()** function returns the sign of a number, indicating whether the number is positive, negative or zero. It returns 1 for positive, -1 for negative and 0 for a zero value.

Math.sign(num)

We can automatically convert the reversedNumber to possess same sign as the number that was received by multiplying it by the value returned by Math.sign() above. i.e

return (reversedNumber * Math.sign(num))

The statement above does the conversion and returns the result from the function as the final answer. For our challenge sample, Math.sign(num) returns -1. When we multiply -1 by 321 we have -321, which is the correct answer(i.e the reversed integer).

Notice how we’ve compressed things a little more to make the solution more concise.

Testing

Testing Correctness with Jest

To execute the tests for this challenge, simply run the following command from your terminal

npm run test IntegerReversal

The results reveal that we passed all tests.

Testing Performance with Jest

Since we considered only one approach to solving this challenge, we carry out no performance comparison.

Practical Application

This challenge is simply a variation of the string reversal challenge and may be used used to test an understanding of JavaScript in coding interviews.

Conclusion

We have now successfully implemented the solution to this challenge despite its unique constraints. Feel free to explore more ways and share in the comment section below. Stay tuned for more mathematical challenges to follow.

Further Reading

For further learning on the techniques and concepts applied above, you may use the following links:

]]>Philip Obosi2019-04-05 09:32:02https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/array-chunking
https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/array-chunkingThis article marks the beginning of our array manipulation algorithms. In this article, we explore different techniques to chunk (split) an array into smaller units.

Array chunking is a tech...]]>

This article marks the beginning of our array manipulation algorithms. In this article, we explore different techniques to chunk (split) an array into smaller units.

Array chunking is a technique used to split very large arrays into smaller groups(sizes) usually for easier manipulation and presentation.

We will learn more array manipulation techniques in our solutions as well as evaluate their performance and examine the practicality of this challenge.

Ready? Let's go!

You should already have your development environment setup for this course. Open the cloned repository and inside the Beginner folder, navigate to the chunkArray folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

The Challenge

Given an array and a chunk size, divide the array into many sub-arrays where each sub-array has the specified length. E.g

Algorithmic Thinking

From the challenge statement above, our function will receive two parameters, namely; the array to be split and the size of each chunk.

The size here refers to the maximum number of elements in each new sub-array.

Thus, we are expected to split the large array into smaller groups of the specified size. In the challenge sample, we split the array of 13 elements into smaller groups of 5, with the last group having only 3 elements because the elements from the supplied array have been exhausted.

In the same manner, we are to write a function that goes through the elements of the array received and split it into groups as specified by the size passed in.

Pretty straight forward, right? I think so too.
Code Implementation
We will now consider four approaches that utilize various techniques in solving this challenge. They are:

Looping through the array

Iterating with the number of chunks

Using .slice()

Recursion

Let's now examine them one at a time.

Looping Through the Array

In this approach, we loop through the array using a for…of loop as we manually break it down into smaller groups.

We initialize an empty array result with which we use to store every smaller group(chunk) that is created. Our intention here is to add each element to a group(sub-array) within our result array until all elements have been assigned.

Within the for…of loop, we use an if statement to check if our result array is currently empty or if the last group(sub-array) created is complete i.e already of the specified size .

If it is, we create a new group(sub-array) with the current value as an element and push it into the result array. If it isn't, we retrieve the last array from result and push the current value into it until the group is complete(i.e the required size is reached).

At the end, we return result which is an array of all the groups(sub-arrays) created throughout the iteration.

Looping Through the Number of Chunks

This is a more concise approach to chunking(grouping) the elements of an array. Here, we use the .splice() method to extract elements of the specified size from the array that is received.

The **.splice()** method is used to modify the content of an array by removing or replacing elements.

It receives two parameters: the starting index and the number of elements from that point to be extracted and returned.

Because .splice() element manipulates the array in place (i.e it changes the received array directly), we use the spread operator … to create a copy which we call arrayCopy so that our operations do not affect the data that is received.

It is from this copy that we continuously extract elements of the specified size using a while loop that will continue to execute for as long as the length of the arrayCopy is greater than 0.

Each sub-array created is then added to the result by calling the .push() method.

At the end, we return the result which is an array of all the groups(sub-arrays) that were created.

In the context of the sample above, we have an array of 13 elements to be grouped in five. Using the **.splice()** method, we start at the beginning(starting index of 0) and extract the first five elements from it into a new array which we now add to our **result** and repeat the process on the remaining 8. This process will continue to run for as long as there are still elements in the array i.e the length of the array is greater than 0.

Using .slice()

The .slice() method is used to extract a portion of an array starting from the specified beginning to end without modifying the original array. It returns a new array containing all elements from the starting index till the end index without including the item at the end index.

In the code snippet below, we use a for-loop to iterate through the array while repeatedly slicing off groups(chunks) of the specified size using the .slice() method. We increment the iterator by the specified size on each iteration in order to start each new group from where the previous one ended.

Again, we accumulate each group in our result array and then return it at the end of the iteration.

Let’s see one final solution.

Recursion

In this approach, we consistently reduce the problem set(i.e the size of the array) by slicing off chunks of the required size until all elements within the array have been grouped. To this effect, we add a conditional at the beginning to serve as the terminating condition such that when the number of remaining elements is less than or equal to the specified size, we simply return all the remaining elements as one group.

Notice that we use the .slice() method here to extract portions of the array as chunks as well as reduce the size of the original array continuously until the terminating condition is met.

All done! Let’s test our solutions.
Testing

Testing Correctness with Jest

To carry out the tests for each solution above, run the command below in your terminal:

npm run test chunkArray

Looping through the array

Iterating with the number of chunks

Using .slice()

Recursion

Yippee!!! We passed all tests. Now, let’s evaluate performance.

Testing Performance with JSPerf

Here, we run a performance test on all four solutions explored above. The image below reveals the result.

After comparing all four solutions, we find that the .slice() method is the fastest of all implementations. It is followed by the recursive approach which is 46% slower.

Practical Application

This challenge is often encountered in coding interviews. In addition, the techniques explored herein are also applicable to batch data processing in real world applications.

That is, when processing very a large data-set listed as one large array, one could use this technique for breaking such data into smaller groups to be processed or presented in batches. This may bring the idea of pagination of lazy-loading to mind although there are usually more sophisticated ways to implement these.

One practical use case may be in developing a quiz app where questions are to be presented in groups of a specified number or size. One could retrieve all questions at once but chunk them into the desired size for each group for presentation of perhaps only five at a time.

Conclusion

We have now considered four major ways to chunk a given array into smaller arrays of the specified size. We also determined using the .slice() method to be the most optimal approach of them all.

In the articles to follow, we will do more array manipulation exercises to strengthen our competence in that area.

Further Reading

For further study of the concepts highlighted above, you may use the following links:

]]>Philip Obosi2019-04-05 09:31:33https://scotch.io/starters/react/react-prerequisites-and-4-es6-things-to-know
https://scotch.io/starters/react/react-prerequisites-and-4-es6-things-to-knowJavaScript has come a long way in the past decade, especially with the ES6 update.

JavaScript’s standardized name is ECMA Script and this version came in 2015. It was named ES2015 o...]]>

JavaScript has come a long way in the past decade, especially with the ES6 update.

JavaScript’s standardized name is ECMA Script and this version came in 2015. It was named ES2015 or ES6 for version 6.

Knowledge of ES6 is important when building React applications. ES6 brought a lot of cool syntax changes to JavaScript that make writing JavaScript much easier.

Terminal

In order to use the React CLI (create-react-app), it is encouraged to learn the command line. This is how we’ll start applications with create-react-app and also start development on our projects.

1. let and const in addition to var

Up until now, you would declare variables in JavaScript using var. ES6 introduced two new ways to declare variables with const and let. Here are the main differences:

const: This variable can not be reassigned. JavaScript will throw an error if we try to reassign a new value

let: This variable can be reassigned. This is similar to var

Why does this matter?const allows us to quickly see that a variable should stay constant; it will not be reassigned. let tells us that we are going to change the value of this. It gives a little more indicator of what the variable will do than var.

2. Arrow Functions (=>)

Arrow functions are what you’ll see the most JavaScript so it’s a good idea to get used to them. In addition to allowing us to write 1-line syntax, arrow functions can change the lexical scope of a function. We won’t have to worry about scope too much in this starter, just be aware.

Arrow functions allow us to simplify our code to a single line and you may see a lot of this in the React code you encounter. Here’s an example of a React function written with and without arrow functions:

The two examples here are the same, but you get a little bit of cleaner code with the ES6 arrow function.

Note: Functions and Arrow Functions are both valid and can be used throughout our code. It is up to you to determine which is the better one to use for each scenario. Stick to your own set of rules so you have consistency across your code.

3. Classes

ES6 brought in JavaScript classes. Classes are just some syntactical sugar for JavaScript. Under the hood, classes are just plain old functions. React code has many classes throughout, but for our starter guide, we’ll be using functions directly.

It is good to be aware that React code you see may use classes. React 16.8 brought us React Hooks which gave React functional components all the same tools as React class components so we’ll stick to functional components.

Component Comparison with State

Here’s an example of a component that uses React state in function and classes:

Notice how much cleaner the functional React component is using React Hooks like useState. For our Starter Guide, we’ll stick to React functional components and React Hooks.

4. Destructuring

Destructuring is used very often in React. Object destructuring and array destructuring are very easy ways to simplify our JavaScript code.

Destructuring lets us simplify multiple tedious lines into a single line.

Object Destructuring

Let’s tackle object destructuring first. ES6 allows us to split our JavaScript across multiple files and then be able to import what we need. For instance, when we want to grab React when using ES6, we can import React from'``react``' . These import statements is where you’ll see object destructuring mostly.

Here’s a simple example of object destructuring.

// create an object
const person = {
name: 'chris',
username: 'chrisoncode'
};
// you could get name like this:
let name = person.name;
let username = person.username;
// or you could get name with destructuring
let { name, username } = person;

Let’s look at object destructuring in React. The following is two ways to write the same thing:

We wouldn’t want to write our code like this; it’s tedious. Let’s write in the clean ES6 syntax and let these transpilers do the heavy lifting for us.

When we did our CodePen example from the previous article, we set up our CodePen to transpile our code with Babel. This is how older browsers will be able to understand our React code.

How do we use Babel?

When we start applications using the React CLI (create-react-app), we’ll automatically get Babel added. If you are adding React to an already existing application, you’ll need to add a build setup yourself using webpack or another similar tool.

The lastIndexOf() method returns the last position within a String object which an element can be found. The search starts from the last position of the String object. ...]]>

Basics

The lastIndexOf() method returns the last position within a String object which an element can be found. The search starts from the last position of the String object. The method will return -1 if the specified parameter cannot be found.

Syntax

2 Parameters

searchParam
This is the string value to search for within the String object - required

startIndex
This is the index at which the search will begin. Search typically begins from the string.length - 1 index, which is the last position of the object. If the length of the provided string is 0, or if no item was found, it returns -1.

Returns a number

The method returns a number whch is the index of the last occurence of the search parameter.

This method is case sensitive

Common Uses and Snippets

Find the last word repitition in a list

With the lastIndexOf() method, the index of the last occurrence of a particular string can be obtained.

This method is a called against a regular expression and returns the matching values in the string. The return value is an array containing the matched values. If no matches are fo...]]>

Basics

This method is a called against a regular expression and returns the matching values in the string. The return value is an array containing the matched values. If no matches are found within the string, null is returned.

The startsWith method takes a string parameter and checks if the calling string starts with the value provided. It returns a Boolean value, true

Basics

The startsWith method takes a string parameter and checks if the calling string starts with the value provided. It returns a Boolean value, true if the string starts with the provided value and false if not. It is case sensitive meaning the case of the search term needs to match that of the calling string.

]]>William Imoh2019-03-26 16:32:03https://scotch.io/starters/react/react-popularity-and-when-not-to-use-react
https://scotch.io/starters/react/react-popularity-and-when-not-to-use-reactThere are many big reasons for why React has become so popular. Let's examine how popular React is, what people like about it, and when we should/shouldn't use React.

Main Benefits of React...]]>

There are many big reasons for why React has become so popular. Let's examine how popular React is, what people like about it, and when we should/shouldn't use React.

Main Benefits of React

There are many big benefits to React, but the main ones are:

Clean programming. By creating your views with React, you get easy-to-read and easy-to-reuse code.

Strong community. If you need a package like a map or a graph, you can bet that there’s a great package that you can install. The strong community means you have a breadth of packages that you can install and use immediately. Less writing for you!

Fast performance. React for small and large projects works very quickly thanks to the Virtual DOM it uses.

Also, on GitHub stars (Stars may not be the best ranking factor. Clicking the star doesn’t always correlate to using in real life), React ranks second behind Vue for stars on JavaScript libraries/frameworks.

React: 119,425 Stars

Vue: 124,544 Stars

Angular: 44,175 Stars

When to use React

React excels because it’s pure JavaScript. If you have a team of JavaScript developers that know the ins and outs of the language, then it’s a great fit.

JavaScript developers will be able to:

Embrace JS

Build components with pure JavaScript

Understand styling with CSS-in-JS

Of course these are quick assumptions. This is not to say that JavaScript developers would have a hard time in the other frameworks. JavaScript developers would excel in any of the JavaScript type frameworks.

The biggest difference for when NOT to use React is when your team doesn’t solely consist of JavaScript developers. Let’s explore why you would want to choose something else.

When NOT to use React

The biggest reason I see for teams not choosing React is if the teams aren’t the strongest in pure JavaScript. You may not want to use React if your team:

Has frontend designers that are familiar with HTML and aren't comfortable with JSX

Has frontend designers that are familiar with CSS

JSX can be somewhat of a non-starter for some designers that are more familiar with HTML. JSX can be learned quickly, but that could be a learning curve that you don't want to apply on your designers.

With React styles, you can use CSS, Sass, and CSS-in-JS. If your app uses CSS or Sass, then your designers will have an easy time jumping into the code base.

If you are using a CSS-in-JS solution like styled-components then there will probably be an adjustment period.

This section won’t be that long because React is a great fit for any team. There just may be a larger learning curve with some teams. It all depends on your project to determine if you want to spend the time on that learning curve.

React is a great fit for any team. There just may be a larger learning curve with some teams.