跟随,学习,进步

SitePoint

SitePoint – Learn HTML, CSS, JavaScript, PHP, Ruby & Responsive Design

https://www.sitepoint.com
转到作者网站

Getting Started with GraphQL and React Native

In 2012, Facebook engineer Nick Schrock started work on a small prototype to facilitate moving away from an old, unsupported partner API that powered the current Facebook News Feed. At the time, this was called “SuperGraph”. Fast forward to today and SuperGraph has helped shape the open-source query language GraphQL, which has been much of the buzzword in recent times. Facebook describes GraphQL as a “query language for APIs and a runtime for fulfilling those queries with your existing data”. Put simply, GraphQL is an alternative to REST that has been steadily gaining popularity since its release. Whereas with REST a developer would usually collate data from a series of endpoint requests, GraphQL allows the developer to send a single query to the server that describes the exact data requirement. Prerequisites For this tutorial, you’ll need a basic knowledge of React Native and some familiarity with the Expo environment. You’ll also need the Expo client installed on your mobile device or a compatible simulator installed on your computer. Instructions on how to do this can be found here. Project Overview In this tutorial, we’re going to demostrate the power of GraphQL in a React Native setting by creating a simple coffee bean comparison app. So that you can focus on all of the great things GraphQL has to offer, I’ve put together the base template for the application using Expo. To get started, you can clone this repo and navigate to the “getting-started” branch, which includes all of our basic views to start adding our GraphQL data to, as well as all of our initial dependencies, which at this stage are: { "expo": "^32.0.0", "react": "16.5.0", "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz", "react-navigation": "^3.6.1" } To clone this branch, you’ll need to open up terminal and run this command: git clone https://github.com/jamiemaison/graphql-coffee-comparison.git To then navigate to the getting-started branch, you move into the newly cloned repo with cd graphql-coffee-comparison and run git checkout getting-started. The next stage is to install our dependencies. To do this, make sure you’re on Node v11.10.1 and run npm install in the root directory of the project. This will add all of the dependencies listed above to your node_modules folder. To start adding GraphQL to our React Native app, we’re going to need to install a few more dependencies that help us perform a few simple GraphQL functions. As is common with modern JavaScript development, you don’t need all of these dependencies to complete the data request, but they certainly help in giving the developer a better chance of structuring some clean, easy-to-read code. The dependencies you’ll need can be installed by running npm install --save apollo-boost react-apollo graphql-tag graphql. Here’s an overview of what these dependencies are: apollo-boost: a zero-configuration way of getting started with GraphQL in React/React Native react-apollo: this provides an integration between GraphQL and the Apollo client graphql-tag: a template literal tag that parses GraphQL queries graphql: the JavaScript reference implementation for GraphQL Once all of the necessary dependencies have finished installing, run npm start. You should now see your familiar Expo window, and if you launch the app (either via a simulator or on a device) then you should see a screen similar to this: In basic terms, this application has two screens that are managed by react-navigation, Home.js and CoffeePage.js. The Home screen contains a simple FlatList that renders all of the coffee beans supplied to its data field. When clicked on, the user is navigated to the CoffeePage for that item, which displays more information about the product. It’s our job to now populate these views with interesting data from GraphQL. Apollo Server Playground There are two main elements to any successful GraphQL transaction: the server holding the data, and the front-end query making the request. For the purposes of this tutorial, we aren’t going to start delving into the wonderful world of server-side code, so I’ve created our server for us ready to go. All you need to do is navigate to yq42lj36m9.sse.codesandbox.io in your favorite browser and leave it running throughout the course of development. For those interested, the server itself is running using apollo-server and contains just enough code to hold the data we need and serve it upon receiving an appropriate query. For further reading, you can head over to apollographql.com to read more about apollo-server. GraphQL Query Basics Before we get into writing the actual code that’s going to request the data we need for our coffee bean comparison app, we should understand just how GraphQL queries work. If you already know how queries work or just want to get started with coding, you can skip ahead to the next section. Note: these queries won’t work with our codesandbox server, but feel free to create your own at codesandbox.io if you’d like to test out the queries. At its simplest level, we can use a flat structure for our queries when we know the shape of the data we’re requesting: QUERY: RESPONSE: { { coffee { "coffee": { blend "blend": "rich" } } } } On the left, we see the GraphQL query requesting the blend field from coffee. This works well when we know exactly what our data structure is, but what about when things are less transparent? In this example, blend returns us a string, but queries can be used to request objects as well: QUERY: RESPONSE: { { coffee { "coffee": { beans { "beans": [ blend { } blend: "rich" } }, } { blend: "smooth" } ] } } Here you can see we are simply requesting the beans object, with only the field blend being returned from that object. Each object in the beans array may very well contain other data other than blend, but GraphQL queries help us request only the data we need, cutting out any extra information that’s not necessary for our application. So what about when we need to be more specific than this? GraphQL provides the capability for many things, but something that allows for extremely powerful data requests is the ability to pass arguments in your query. Take the following example: QUERY: RESPONSE: { { coffee(companyId: "2") { "coffee": { beans { "beans": [ blend { } blend: "rich" } }, } { blend: "smooth" } ] } } What we see is that we can pass an argument — in this case, the companyId — which ensures that we are only returned beans from one particular company. With REST, you can pass a single set of arguments via query params and URL segments, but with GraphQL querying every single field, it can get its own set of arguments. This allows GraphQL to be a dynamic solution for making multiple API fetches per request. The post Getting Started with GraphQL and React Native appeared first on SitePoint.


macOS Catalina: 5 Things Web Developers & Designers Should Know

macOS Catalina is here and available for download, and you've no doubt heard all about the breakup of iTunes and the new consumer-oriented entertainment apps shipping with the system. But what do developers, designers, and other tech professionals need to know? We run through the key points. 32-bit Support Ends with Catalina Are you relying on some older, obscure native app for a specific function, as so many developers and designers do? Your Catalina update could throw you a wildcard: it's the first macOS release that drops support for 32-bit apps. During the setup process, you'll be given a list of installed apps that will no longer open after the update. If you want to keep using that tool, it's time to hit up the developer for a long-overdue update... or stay on Mojave for a while longer yet. A Cross-Platform Catalyst Mojave brought iOS ports of the News, Stocks, Voice Memos and Home apps to macOS. In Catalina, Apple is opening the tools that enabled these ports up to developers under the name of Catalyst. While this doesn't directly affect web development work, it does make iOS a more attractive native development platform, which may inform your future platform choices. And if Apple's plan to reinvigorate stale macOS third-party app development with some of the action from iOS works, you could incorporate better productivity and development apps into your workflow in the near future. For now, Catalyst is available to developers of iPad apps — we expect that to broaden in the future. Voice Control Catalina offers accessibility improvements in the form of improved Voice Control for those who have difficulty seeing, or using keyboards and mice. Of course, developers should ensure that their apps work as well as they can with this tool, because it's the right thing to do. Developers are known for their love of keyboard shortcut mastery, but no doubt the ability to create custom commands has inspired determined lifehackers. What if you never had to take your cursor or eyes off of VS Code to run other frequent workflows? We look forward to seeing what the community comes up with. Screen Time Do you waste too much time using your computer for mindless entertainment, forcing you to stay up late making up the time productively? Or are you a workaholic who just can't find the will to shut off and disconnect? If you're like most of us in the industry, you're a mix of the two. Catalina introduces a variant of the Screen Time app that's been on iOS for a couple of years now. Screen Time for macOS provides you with visual analytics that help you understand the way you're spending time on your device, which can often lead to some unexpected epiphanies. It also lets you schedule downtime, forcing you off the computer and into the real world at the right time. As with iOS, you can also set time limits for specific apps, and there are some ways to moderate your web content usage without outright blocking your web browser from opening. Sidecar: The Most Expensive Secondary Display You'll Ever Own For developers, designers, and all other web professionals, the real headline feature of Catalina is Sidecar. Sidecar turns your iPad into a secondary display for your Mac, and it's really easy to enable (provided you have the requisite tablet, which is not included with the operating system update). The best reason to use Sidecar over a standard display is Apple Pencil integration. Designers will love the ability to draw directly on the screen when using Sketch and Illustrator without switching devices all the time. You can even mirror your Mac's screen if you'd like an unobstructed view of what you're sketching on one side. Most of us will use Sidecar as a place to dump Slack or a terminal window, but in any case, it's clear it'll be the most beneficial update for many of us. How'd You Go? Let us know how you went with the upgrade, and what you've enjoyed most so far. We always recommend waiting a few days for the bugs to shake out — especially with Apple's recent track record — but initial reports suggest the release version is pretty solid after all. The post macOS Catalina: 5 Things Web Developers & Designers Should Know appeared first on SitePoint.


9 of the Best Animation Libraries for UI Designers

This is the latest update to our guide to helping you choose the right animation library for each task. We're going to run-through 9 free, well-coded animation libraries best-suited to UI design work — covering their strengths and weaknesses, and when to choose each one. Take your CSS animations to the next level with our Animating with CSS course by Donovan Hutchinson, the man behind CSS Animation Rocks. Front-end web design has been through a revolution in the last decade. In the late naughties, most of us were still designing static magazine layouts. Nowadays, we're building “digital machines” with thousands of resizing, coordinated, moving parts. Quite simply, great UI designers need to be great animators too — with a solid working understanding of web animation techniques. Keep in mind that we're looking at each library from the perspective of a code-savvy UI designer, not as a “code guru” developer. Some of these libraries are pure CSS. Others are JavaScript, but none require anything more than basic HTML/CSS understanding to be useful. Link the library; add a CSS class. Quite simply, great UI designers need to be great animators with a rock-solid understanding of the underlying tech. This is the latest update to our guide to helping you choose the right animation library for each task. We're going to run-through 9 free, well-coded animation libraries best-suited to UI design work – their strengths and weaknesses and when to choose each one. Some are pure CSS. Others are JavaScript, but none require anything more than basic HTML/CSS understanding to be used. Enjoy. The 2017 Top 9 Animation Libraries List Animate.css Bounce.js AnimeJS Magic Animations DynCSS CSShake Hover.CSS Velocity.js AniJS Animate.css Animate.css is one of the smallest and most easy-to-use CSS animation libraries available. Applying the Animate library to your project is as simple as adding the required CSS classes to your HTML elements. You can also use jQuery to call the animations on a particular event. Creators: Daniel Eden Released: 2013 Current Version: 3.5.2 Most Recent Update: April 2017 Popularity: 41,000+ stars on GitHub Description: "A cross-browser library of CSS animations. As easy to use as an easy thing." Library Size: 43 kB GitHub: https://github.com/daneden/animate.css License: MIT As of mid-2017, it still one of the most popular and widely-used CSS animation libraries and its minified file is small enough (16.6kb) for inclusion in mobile websites as well. It has 41,000 stars on Github and is used as a component in many larger projects. Animate.css is still under active development after 4 years. We feel that this is one of the simplest and most robust animation libraries and would definitely recommend you to use this in your next project. Bounce.js Bounce.js is a tool and javascript library that focusses on providing a selection of unique bouncy CSS animations to your website. This project is open-source with its code on GitHub. Creators: Tictail Released: 2014 Current Version: 0.8.2 Most Recent Update: Feb 2015 Popularity: 4,967+ stars on GitHub Description: "Create beautiful CSS3 powered animations in no time." Library Size: 16 kB GitHub: https://github.com/tictail/bounce.js License: MIT Bounce.js is a neat animation library shipped with about ten animation 'pre-sets' – hence the small size of the library. As with animate.css, the animations are smooth and flawless. You might want to consider using this library if your needs focus on 'pop and bubble' animation types and could benefit from a lower file size overhead. AnimeJS AnimeJS is described as a lightweight JavaScript animation library that 'works with any CSS Properties, individual CSS transforms, SVG or any DOM attributes, and JavaScript Objects'. It's pretty awesome – so awesome in fact, that the GIF capture I took below can't do justice to how smooth and buttery the motion is. This project is available on GitHub. Creator: Julian Garnier Released: 2016 Current Version: 2.0.2 Most Recent Update: March 2017 Popularity: 12,222+ stars on GitHub Description: "JavaScript Animation Engine." Library Size: 10.9kB GitHub: https://github.com/juliangarnier/anime License: MIT AnimeJS is only newcomer to our list but has won a lot of converts in the 12 months since it's creation. It's incredibly versatile and powerful and wouldn't be out of place being used within HTML games. The only real question is 'is it overkill for simple web apps'? Maybe, but as its fast, small and relatively easy to learn, it's hard to find fault with it. Magic Animations Magic Animations has been one impressive animation libraries available. It has many different animations, many of which are quite unique to this library. As with Animate.css, you can implement Magic by simply importing the CSS file. You can also make use of the animations from jQuery. This project offers a particularly cool demo application. The post 9 of the Best Animation Libraries for UI Designers appeared first on SitePoint.


Create a Cron Job on AWS Lambda

Cron jobs are really useful tools in any Linux or Unix-like operating systems. They allow us to schedule scripts to be executed periodically. Their flexibility makes them ideal for repetitive tasks like backups and system cleaning, but also data fetching and data processing. For all the good things they offer, cron jobs also have some downsides. The main one is that you need a dedicated server or a computer that runs pretty much 24/7. Most of us don't have that luxury. For those of us who don't have access to a machine like that, AWS Lambda is the perfect solution. AWS Lambda is an event-driven, serverless computing platform that's a part of the Amazon Web Services. It’s a computing service that runs code in response to events and automatically manages the computing resources required by that code. Not only is it available to run our jobs 24/7, but it also automatically allocates the resources needed for them. Setting up a Lambda in AWS involves more than just implementing a couple of functions and hoping they run periodically. To get them up and running, several services need to be configured first and need to work together. In this tutorial, we'll first go through all the services we'll need to set up, and then we'll implement a cron job that will fetch some updated cryptocurrency prices. Understanding the Basics As we said earlier, some AWS services need to work together in order for our Lambda function to work as a cron job. Let's have a look at each one of them and understand their role in the infrastructure. S3 Bucket An Amazon S3 bucket is a public cloud storage resource available in Amazon Web Services' (AWS) Simple Storage Service (S3), an object storage offering. Amazon S3 buckets, which are similar to file folders, store objects, which consist of data and its descriptive metadata. — TechTarget Every Lambda function needs to be prepared as a “deployment package”. The deployment package is a .zip file consisting of the code and any dependencies that code might need. That .zip file can then be uploaded via the web console or located in an S3 bucket. IAM Role An IAM role is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS. — Amazon We’ll need to manage permissions for our Lambda function with IAM. At the very least it should be able to write logs, so it needs access to CloudWatch Logs. This is the bare minimum and we might need other permissions for our Lambda function. For more information, the AWS Lambda permissions page has all the information needed. CloudWatch Events Rule CloudWatch Events support cron-like expressions, which we can use to define how often an event is created. We'll also need to make sure that we add our Lambda function as a target for those events. Lambda Permission Creating the events and targeting the Lambda function isn’t enough. We'll also need to make sure that the events are allowed to invoke our Lambda function. Anything that wants to invoke a Lambda function needs to have explicit permission to do that. These are the building blocks of our AWS Lambda cron job. Now that we have an idea of all the moving parts of our job, let's see how we can implement it on AWS. Implementing a Cron Job on AWS A lot of the interactions we described earlier are taken care of by Amazon automatically. In a nutshell, all we need to do is to implement our service (the actual lambda function) and add rules to it (how often and how the lambda will be executed). Both permissions and roles are taken care of by Amazon; the defaults provided by Amazon are the ones we'll be using. Lambda function First, let's start by implementing a very simple lambda function. In the AWS dashboard, use the Find Services function to search by lambda. In the lambda console, select Create a function. At this point, we should be in Lambda > Functions > reate Function. To get things going, let's start with a static log message. Our service will only be a print function. For this, we'll use Node.js 10x as our runtime language. Give it a function name, and on Execution Role let's stay with Create a new role with basic lambda permissions. This is a basic set of permissions on IAM that will allow us to upload logs to Amazon CloudWatch logs. Click Create Function. Our function is now created with an IAM Role. In the code box, substitute the default code with the following: exports.handler = async (event) => { console.log("Hello Sitepoint Reader!"); return {}; }; To check if the code is executing correctly, we can use the Test function. After giving a name to our test, it will execute the code and show its output in the Execution Result field just below our code. If we test the code above we can see that we have no response, but in the function logs, we can see we have our message printed. This indicates that our service is running correctly so we can proceed with our cron implementation. The post Create a Cron Job on AWS Lambda appeared first on SitePoint.


Cloning Tinder Using React Native Elements and Expo

Making pixel-perfect layouts on mobile is hard. Even though React Native makes it easier than its native counterparts, it still requires a lot of work to get a mobile app to perfection. In this tutorial, we’ll be cloning the most famous dating app, Tinder. We’ll then learn about a UI framework called React Native Elements, which makes styling React Native apps easy. Since this is just going to be a layout tutorial, we’ll be using Expo, as it makes setting things up much easier than plain old react-native-cli. We’ll also be making use of a lot of dummy data to make our app. We’ll be making a total of four screens—Home, Top Picks, Profile, and Messages. Prerequisites For this tutorial, you need a basic knowledge of React Native and some familiarity with Expo. You’ll also need the Expo client installed on your mobile device or a compatible simulator installed on your computer. Instructions on how to do this can be found here. You also need to have a basic knowledge of styles in React Native. Styles in React Native are basically an abstraction similar to that of CSS, with just a few differences. You can get a list of all the properties in the styling cheatsheet. Throughout the course of this tutorial we’ll be using yarn. If you don’t have yarn already installed, install it from here. Also make sure you’ve already installed expo-cli on your computer. If it’s not installed already, then go ahead and install it: $ yarn global add expo-cli To make sure we’re on the same page, these are the versions used in this tutorial: Node 11.14.0 npm 6.4.1 yarn 1.15.2 expo 2.16.1 Make sure to update expo-cli if you haven’t updated in a while, since expo releases are quickly out of date. We’re going to build something that looks like this: If you just want to clone the repo, the whole code can be found on GitHub. Getting Started Let’s set up a new Expo project using expo-cli: $ expo init expo-tinder It will then ask you to choose a template. You should choose tabs and hit Enter. Then it will ask you to name the project. Type expo-tinder and hit Enter again. Lastly, it will ask you to press y to install dependencies with yarn or n to install dependencies with npm. Press y. This bootstraps a brand new React Native app using expo-cli. React Native Elements React Native Elements is a cross-platform UI Toolkit for React Native with consistent design across Android, iOS and Web. It’s easy to use and completely built with JavaScript. It’s also the first UI kit ever made for React Native. It allows us to fully customize styles of any of our components the way we want so every app has its own unique look and feel. It’s also open source and backed by a community of awesome developers. You can build beautiful applications easily. Cloning Tinder UI We’ve already created a project named expo-tinder. To run the project, type this: $ yarn start Press i to run the iOS Simulator. This will automatically run the iOS Simulator even if it’s not opened. Press a to run the Android Emulator. Note that the emulator must be installed and started already before typing a. Otherwise it will throw an error in the terminal. It should look like this: The post Cloning Tinder Using React Native Elements and Expo appeared first on SitePoint.


How to Build a News App with Svelte

Svelte is a new JavaScript UI library that's similar in many ways to modern UI libraries like React. One important difference is that it doesn't use the concept of a virtual DOM. In this tutorial, we'll be introducing Svelte by building a news application inspired by the Daily Planet, a fictional newspaper from the Superman world. About Svelte Svelte makes use of a new approach to building users interfaces. Instead of doing the necessary work in the browser, Svelte shifts that work to a compile-time phase that happens on the development machine when you're building your app. In a nutshell, this is how Svelte works (as stated in the official blog): Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM. As a result, you're able to write ambitious applications with excellent performance characteristics. Svelte is faster than the most powerful frameworks (React, Vue and Angular) because it doesn't use a virtual DOM and surgically updates only the parts that change. We'll be learning about the basic concepts like Svelte components and how to fetch and iterate over arrays of data. We'll also learn how to initialize a Svelte project, run a local development server and build the final bundle. Prerequisites You need to have a few prerequisites, so you can follow this tutorial comfortably, such as: Familiarity with HTML, CSS, and JavaScript (ES6+), Node.js and npm installed on your development machine. Node.js can be easily installed from the official website or you can also use NVM for easily installing and managing multiple versions of Node in your system. We'll be using a JSON API as a source of the news for our app, so you need to get an API key by simply creating an account for free and taking note of your API key. Getting Started Now, let's start building our Daily Planet news application by using the degit tool for generating Svelte projects. You can either install degit globally on your system or use the npx tool to execute it from npm. Open a new terminal and run the following command: npx degit sveltejs/template dailyplanetnews Next, navigate inside your project's folder and run the development server using the following commands: cd dailyplanetnews npm run dev Your dev server will be listening from the http://localhost:5000 address. If you do any changes, they'll be rebuilt and live-reloaded into your running app. Open the main.js file of your project, and you should find the following code: import App from './App.svelte'; const app = new App({ target: document.body, props: { name: 'world' } }); export default app; This is where the Svelte app is bootstrapped by creating and exporting an instance of the root component, conventionally called App. The component takes an object with a target and props attributes. The target contains the DOM element where the component will be mounted, and props contains the properties that we want to pass to the App component. In this case, it's just a name with the world value. Open the App.svelte file, and you should find the following code: <script> export let name; </script> <style> h1 { color: purple; } </style> <h1>Hello {name}!</h1> This is the root component of our application. All the other components will be children of App. Components in Svelte use the .svelte extension for source files, which contain all the JavaScript, styles and markup for a component. The export let name; syntax creates a component prop called name. We use variable interpolation—{...}—to display the value passed via the name prop. You can simply use plain old JavaScript, CSS, and HTML that you are familiar with to create Svelte components. Svelte also adds some template syntax to HTML for variable interpolation and looping through lists of data, etc. Since this is a small app, we can simply implement the required functionality in the App component. In the <script> tag, import the onMount() method from "svelte" and define the API_KEY, articles, and URL variables which will hold the news API key, the fetched news articles and the endpoint that provides data: <script> export let name; import { onMount } from "svelte"; const API_KEY = "<YOUR_API_KEY_HERE>"; const URL = `https://newsapi.org/v2/everything?q=comics&sortBy=publishedAt&apiKey=${API_KEY}`; let articles = []; </script> onMount is a lifecycle method. Here’s what the official tutorial says about that: Every component has a lifecycle that starts when it is created and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle. The one you'll use most frequently is onMount, which runs after the component is first rendered to the DOM. Next, let's use the fetch API to fetch data from the news endpoint and store the articles in the articles variable when the component is mounted in the DOM: <script> // [...] onMount(async function() { const response = await fetch(URL); const json = await response.json(); articles = json["articles"]; }); </script> Since the fetch() method returns a JavaScript Promise, we can use the async/await syntax to make the code look synchronous and eliminate callbacks. The post How to Build a News App with Svelte appeared first on SitePoint.


Real-time Location Tracking with React Native and PubNub

With ever-increasing usage of mobile apps, geolocation and tracking functionality can be found in a majority of apps. Real-time geolocation tracking plays an important role in many on-demand services, such as these: taxi services like Uber, Lyft or Ola food Delivery services like Uber Eats, Foodpanda or Zomato monitoring fleets of drones In this guide, we’re going use React Native to create a real-time location tracking apps. We’ll build two React Native apps. One will act as a tracking app (called “Tracking app”) and the other will be the one that’s tracked (“Trackee app”). Here’s what the final output for this tutorial will look like: [video width="640" height="480" mp4="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2019/09/1569381508tracking.mp4"][/video] Prerequisites This tutorial requires a basic knowledge of React Native. To set up your development machine, follow the official guide here. Apart from React Native, we’ll also be using PubNub, a third-party service that provides real-time data transfer and updates. We’ll use this service to update the user coordinates in real time. Register for a free PubNub account here. Since we’ll be using Google Maps on Android, we’ll also need a Google Maps API key, which you can obtain on the Google Maps Get API key page. To make sure we’re on the same page, these are the versions used in this tutorial: Node v10.15.0 npm 6.4.1 yarn 1.16.0 react-native 0.59.9 react-native-maps 0.24.2 pubnub-react 1.2.0 Getting Started If you want to have a look at the source code of our Tracker and Trackee apps right away, here are their GitHub links: Trackee App repo Tracker App repo Let’s start with the Trackee app first. Trackee App To create a new project using react-native-cli, type this in the terminal: $ react-native init trackeeApp $ cd trackeeApp Now let’s get to the fun part — the coding. Add React Native Maps Since we’ll be using Maps in our app, we’ll need a library for this. We’ll use react-native-maps. Install react-native-maps by following the installation instructions here. Add PubNub Apart from maps, we’ll also install the PubNub React SDK to transfer our data in real time: $ yarn add pubnub-react After that, you can now run the app: $ react-native run-ios $ react-native run-android You should see something like this on your simulator/emulator: The post Real-time Location Tracking with React Native and PubNub appeared first on SitePoint.


How to Build Your First Telegram Chatbot with Node.js

So, this morning you woke up with the idea to develop a way to store and label interesting articles you've read. After playing with the idea, you figure a Telegram chatbot is the most convenient solution for this problem. In this guide, we'll walk you through everything you need to know to build your first Telegram chatbot using JavaScript and Node.js. To get started, we have to register our new bot with the so-called Botfather to receive our API access token. Bot Registration with @BotFather The first step towards our very own Telegram bot is registering the bot with the BotFather. The BotFather is a bot itself that makes your life much easier. It helps you with registering bots, changing the bot description, adding commands, and providing you with the API token for your bot. The API token is the most important step, as this allows you to run the code that can perform tasks for the bot. 1. Finding the BotFather The BotFather can be found on Telegram by searching for 'BotFather'. Click on the official BotFather, indicated with the white checkmark icon in the blue circle. 2. Registering a New Bot Now we've found BotFather, let’s talk to him! You can start the conversation by typing /newbot. BotFather will ask you to choose a name for your both. This name can be anything and doesn’t have to be unique. To keep things simple, I named my bot ArticleBot. Next, you will be prompted to input a username for the bot. The username must be unique and end in bot. Therefore, I chose michiel_article_bot, as that username was not yet taken. This will also be the username you use for looking up the bot in Telegram's search field. FatherBot will return a success message with your token to access the Telegram HTTP API. Make sure to store this token safely, and certainly don't share it with anyone else. 3. Modifying the Bot We can further modify the bot by adding a description or setting the commands we wish the bot to know. You can message the bot with the text /setcommands. It will show you how to input the commands with the format command1 - Description. The post How to Build Your First Telegram Chatbot with Node.js appeared first on SitePoint.


How to Build Unique, Beautiful Websites with Tailwind CSS

When thinking about what CSS framework to use for a new project, options like Bootstrap and Foundation readily jump to mind. They’re tempting to use because of their ready-to-use, pre-designed components, which developers can use with ease right away. This approach works well with relatively simple websites with a common look and feel. But as soon as we start building more complex, unique sites with specific needs, a couple of problems arise. At some point, we need to customize certain components, create new components, and make sure the final codebase is unified and easy to maintain after the changes. It's hard to satisfy the above needs with frameworks like Bootstrap and Foundation, which give us a bunch of opinionated and, in many cases, unwanted styles. As a result, we have to continuously solve specificity issues while trying to override the default styles. It doesn't sound like a fun job, does it? Ready-to-use solutions are easy to implement, but inflexible and confined to certain boundaries. On other hand, styling web sites without a CSS framework is powerful and flexible, but isn’t easy to manage and maintain. So, what’s the solution? The solution, as always, is to follow the golden middle. We need to find and apply the right balance between the concrete and abstract. A low-level CSS framework offers such a balance. There are several frameworks of this kind, and in this tutorial, we'll explore the most popular one, Tailwind CSS. What Is Tailwind? Tailwind is more than a CSS framework, it's an engine for creating design systems. — Tailwind website Tailwind is a collection of low-level utility classes. They can be used like lego bricks to build any kind of components. The collection covers the most important CSS properties, but it can be easily extended in a variety of ways. With Tailwind, customization isn’t pain in the neck anymore. The framework has great documentation, covering every class utility in detail and showing the ways it can be customized. All modern browsers, and IE11+, are supported. Why Using Utility-first Framework? A low-level, utility-first CSS framework like Tailwind has a plenty of benefits. Let's explore the most significant of them: You have greater control over elements' appearance. We can change and fine-tune an element's appearance much more easily with utility classes. It's easy to manage and maintain in large projects, because you only maintain HTML files, instead of a large CSS codebase. It's easier to build unique, custom website designs without fighting with unwanted styles. It's highly customizable and extensible, which gives us unlimited flexibility. It has a mobile-first approach and easy implementation of responsive design patterns. There's the ability to extract common, repetitive patterns into custom, reusable components — in most cases without writing a single line of custom CSS. It has self-explanatory classes. We can imagine how the styled element looks only by reading the classes. Finally, as Tailwind's creators say: it's just about impossible to think this is a good idea the first time you see it — you have to actually try it. So, let's try it! Getting Started with Tailwind To demonstrate Tailwind's customization features, we need to install it via npm: npm install tailwindcss The next step is to create a styles.css file, where we include the framework styles using the @tailwind directive: @tailwind base; @tailwind components; @tailwind utilities; After that, we run the npx tailwind init command, which creates a minimal tailwind.config.js file, where we'll put our customization options during the development. The generated file contains the following: module.exports = { theme: {}, variants: {}, plugins: [], } The next step is to build the styles in order to use them: npx tailwind build styles.css -o output.css Finally, we link the generated output.css file and Font Awesome in our HTML: <link rel="stylesheet" type="text/css" href="output.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css"> And now, we’re ready to start creating. Building a One-page Website Template In the rest of the tutorial, we'll build a one-page website template using the power and flexibility of Tailwind's utility classes. Here you can see the template in action. I'm not going to explain every single utility (which would be boring and tiresome) so I suggest you to use the Tailwind cheatsheet as a quick reference. It contains all available utilities with their effect, plus direct links to the documentation. We'll build the template section by section. They are Header, Services, Projects, Team, and Footer. We firstly wrap all section in a container: <div class="container mx-auto"> <!-- Put the sections here --> </div> Header (Logo, Navigation) The first section — Header — will contain a logo on the left side and navigation links on the right side. Here’s how it will look: Now, let's explore the code behind it. <div class="flex justify-between items-center py-4 bg-blue-900"> <div class="flex-shrink-0 ml-10 cursor-pointer"> <i class="fas fa-drafting-compass fa-2x text-orange-500"></i> <span class="ml-1 text-3xl text-blue-200 font-semibold">WebCraft</span> </div> <i class="fas fa-bars fa-2x visible md:invisible mr-10 md:mr-0 text-blue-200 cursor-pointer"></i> <ul class="hidden md:flex overflow-x-hidden mr-10 font-semibold"> <li class="mr-6 p-1 border-b-2 border-orange-500"> <a class="text-blue-200 cursor-default" href="#">Home</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Services</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Projects</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Team</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">About</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Contacts</a> </li> </ul> </div> As you can see, the classes are pretty self-explanatory as I mentioned above. We'll explore only the highlights. First, we create a flex container and center its items horizontally and vertically. We also add some top and bottom padding, which Tailwind combines in a single py utility. As you may guess, there’s also a px variant for left and right. We'll see that this type of shorthand is broadly used in many of the other utilities. As a background color, we use the darkest blue (bg-blue-900) from Tailwind's color palette. The palette contains several colors with shades for each color distributed from 100 to 900. For example, blue-100, blue-200, blue-300, etc. In Tailwind, we apply a color to a property by specifying the property followed by the color and the shade number. For example, text-white, bg-gray-800, border-red-500. Easy peasy. For the logo on the left side, we use a div element, which we set not to shrink (flex-shrink-0) and move it a bit away from the edge by applying the margin-left property (ml-10). Next we use a Font Awesome icon whose classes perfectly blend with those of Tailwind. We use one of them to make the icon orange. For the textual part of the logo, we use big, light blue, semi-bolded text, with a small offset to the right. In the middle, we add an icon that will be visible only on mobile. Here we use one of the responsive breakpoint prefixes (md). Tailwind, like Bootstrap and Foundation, follows the mobile-first approach. This means that when we use utilities without prefix (visible), they apply all the way from the smallest to the largest devices. If we want different styling for different devices, we need to use the breakpoint prefixes. So, in our case the icon will be visible on small devices, and invisible (md:invisible) on medium and beyond. At the right side we put the nav links. We style the Home link differently, showing that it’s the active link. We also move the navigation from the edge and set it to be hidden on overflow (overflow-x-hidden). The navigation will be hidden (hidden) on mobile and set to flex (md:flex) on medium and beyond. You can read more about responsiveness in the documentation. Services Let's now create the next section, Services. Here’s how it will look: And here’s the code: <div class="w-full p-6 bg-blue-100"> <div class="w-48 mx-auto pt-6 border-b-2 border-orange-500 text-center text-2xl text-blue-700">OUR SERVICES</div> <div class="p-2 text-center text-lg text-gray-700">We offer the best web development solutions.</div> <div class="flex justify-center flex-wrap p-10"> <div class="relative w-48 h-64 m-5 bg-white shadow-lg"> <div class="flex items-center w-48 h-20 bg-orange-500"> <i class="fas fa-bezier-curve fa-3x mx-auto text-white"></i> </div> <p class="mx-2 py-2 border-b-2 text-center text-gray-700 font-semibold uppercase">UI Design</p> <p class="p-2 text-sm text-gray-700">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac est massa.</p> <div class="absolute right-0 bottom-0 w-8 h-8 bg-gray-300 hover:bg-orange-300 text-center cursor-pointer"> <i class="fas fa-chevron-right mt-2 text-orange-500"></i> </div> </div> ... </div> </div> We create a section with light blue background. Then we add an underlined title and a subtitle. Next, we use a flex container for the services items. We use flex-wrap so the items will wrap on resize. We set the dimensions for each card and add some space and a drop shadow. Each card has a colored section with a topic icon, a title, and a description. And we also put a button with an icon in the bottom-right corner. Here we use one of the pseudo-class variants (hover, focus, etc.). They’re used in the same way as responsive breakpoints. We use the pseudo-class prefix, followed by a colon and the property name (hover:bg-orange-300). You can learn more about pseudo-class variants in the documentation. For brevity, I show the code only for the first card. The other ones are similar. You have to change only the colors, icons, and titles. See the final HTML file on GitHub repo for a reference. The post How to Build Unique, Beautiful Websites with Tailwind CSS appeared first on SitePoint.


How to Automatically Optimize Responsive Images in Gatsby

Image optimization — at least in my experience — has always been a major pain when building speedy websites. Balancing image quality and bandwidth efficiency is a tough act without the right tools. Photo editing tools such as Photoshop are great for retouching, cropping and resizing bitmap images. Unfortunately, they are not that good at creating 100% optimized images for the web. Luckily, we have extension packages for build tools that can optimize images for us quickly: Gulp: gulp-imagemin Grunt: grunt-imagemin Webpack: imagemin-webpack Parcel: parcel-plugin-imagemin Unfortunately, image optimization alone is not enough. You need to make sure that the entire website is responsive and looks great at all screen sizes. This can easily be done through CSS, but here lies the problem: Should you optimize your image for large screens or small screens? If the majority of your audience is using mobile devices to access your site, then the logical choice is to optimize images for small screens. However, it's likely that a significant source of revenue is coming from visitors with large screens over 17". You definitely wouldn't want to neglect them. Luckily, we have technology that allows us to deliver optimized responsive images for different screen sizes. This means we need to generate multiple optimized images with different resolutions fit for specific screen sizes or responsive breakpoints. For WordPress site owners, this kind of image optimization requires the use of a plugin and a third-party service. The creation of these responsive images cannot be done on the hosting server without significantly slowing down the site for users, hence the need for a third-party service. If you are using Gatsby to run your website, then you are in luck. This feature is built-in and already configured for you to optimize your responsive images. You just need to drop in some images and write a bit of code to link up your responsive images with your web page. When you run the gatsby build command, the images are optimized for you. This saves you from requiring a third-party service to perform the optimization for you. It's simply done on your deployment machine. In the subsequent sections, we are going to learn: How image optimization works in Gatsby How to optimize images on a web page How to optimize images in a Markdown post Prerequisites Before we start, I would like to note that this tutorial is for developers who are just starting with Gatsby and would like to learn specifically about how to handle images. I am going to assume you already have a good foundation in the following topics: The post How to Automatically Optimize Responsive Images in Gatsby appeared first on SitePoint.


Create an Offline-first React Native App Using WatermelonDB

React Native has different database storage mechanisms for different mobile app purposes. Simple structures — such as user settings, app settings, and other key-value pair data — can be handled easily using async storage or secure storage. Other applications — such as Twitter clones — fetch data from the server and directly show it to the user. They maintain a cache of data, and if a user needs to interact with any document, they call the APIs directly. So not all the applications require a database. When We Need a Database Applications such as the Nozbe (a to-do app), Expense (a tracker), and SplitWise (for in-app purchases), need to work offline. And to do so, they need a way to store data locally and sync it up with the server. This type of application is called an offline first app. Over time, these apps collect a lot of data, and it becomes harder to manage that data directly — so a database is needed to manage it efficiently. Options in React Native When developing an app, choose the database that best fits your requirements. If two options are available, then go with the one that has better documentation and quicker response to issues. Below are some of the best known options available for React Native: WatermelonDB: an open-source reactive database that can be used with any underlying database. By default, it uses SQLite as the underlying database in React Native. SQLite (React Native, Expo): the oldest, most used, battle-tested and well-known solution. It’s available for most of the platforms, so if you’ve developed an application in another mobile app development framework, you might already be familiar with it. Realm (React Native): an open-source solution, but it also has an enterprise edition with lots of other features. They have done a great job and many well-known companies use it. FireBase (React Native, Expo): a Google service specifically for the mobile development platform. It offers lots of functionality, storage being just one of them. But it does require you to stay within their ecosystem to utilize it. RxDB: a real-time database for the Web. It has good documentation, a good rating on GitHub (> 9K stars), and is also reactive. Prerequisites I assume you have knowledge about basic React Native and its build process. We’re going to use react-native-cli to create our application. I’d also suggest setting up an Android or iOS development environment while setting up the project, as you may face many issues, and the first step in debugging is keeping the IDE (Android Studio or Xcode) opened to see the logs. Note: you can check out the official guide for installing dependencies here for more information. As the official guidelines are very concise and clear, we won’t be covering that topic here. To set up a virtual device or physical device, follow these guides: using a physical device using a virtual device Note: there’s a more JavaScript-friendly toolchain named Expo. The React Native community has also started promoting it, but I haven’t come across a large-scale, production-ready application that uses Expo yet, and Expo port isn’t currently available for those using a database such as Realm — or in our case, WatermelonDB. App Requirements We’ll create a movie search application with a title, poster image, genre, and release date. Each movie will have many reviews. The application will have three screens. Home will show two buttons — one to generate dummy records, and a second to add new movie. Below it, there will be one search input that can be used to query movie titles from the database. It will show the list of movies below the search bar. If any name is searched, the list will only show the searched movies. Clicking on any movie will open a Movie Dashboard, from where all its reviews can be checked. A movie can be edited or deleted, or a new review can be added from this screen. The third screen will be Movie Form, which is used to create/update a movie. The source code is available on GitHub. Why We Chose WatermelonDB (features) We need to create an offline-first application, so a database is a must. Features of WatermelonDB Let’s look at some of the features of WatermelonDB. Fully observable A great feature of WatermelonDB is its reactive nature. Any object can be observed using observables, and it will automatically rerender our components whenever the data changes. We don’t have to make any extra efforts to use WatermelonDB. We wrap the simple React components and enhance them to make them reactive. In my experience, it just works seamlessly, and we don’t have to care about anything else. We make the changes in the object and our job’s done! It’s persisted and updated at all the places in the application. SQLite under the hood for React Native In a modern browser, just-in-time compilation is used to improve speed, but it’s not available in mobile devices. Also, the hardware in mobile devices is slower than in computers. Due to all these factors, JavaScript apps run slower in a mobile application. To overcome this, WatermelonDB doesn’t fetch anything until it’s needed. It uses lazy loading and SQLite as an underlying database on a separate thread to provide a fast response. Sync primitives and sync adapter Although WatermelonDB is just a local database, it also provides sync primitives and sync adapters. It makes it pretty easy to use with any of our own back-end databases. We just need to conform to the WatermelonDB sync protocol on the back end and provide the endpoints. Further features include: Statically typed using Flow Available for all platforms Dev Env and WatermelonDB Setup (v0.0) We’re going to use react-native-cli to create our application. Note: you may be able to use it with ExpoKit or Ejecting from Expo. If you want to skip this part then clone the source repo and checkout the v0.0 branch. Start a new project: react-native init MovieDirectory cd MovieDirectory Install dependencies: npm i @nozbe/watermelondb @nozbe/with-observables react-navigation react-native-gesture-handler react-native-fullwidth-image native-base rambdax Below is the list of installed dependencies and their uses: native-base: a UI library that will be used for look and feel of our app. react-native-fullwidth-image: for showing full-screen responsive images. (Sometimes it can be a pain to calculate the width, height and also maintain aspect ratio. So it’s better to use an existing community solution.) @nozbe/watermelondb: the database we’ll be using. @nozbe/with-observables: contains the decorators (@) that will be used in our models. react-navigation: used for Managing routes/screens react-native-gesture-handler: the dependency for react-navigation. rambdax: used to generate a random number while creating dummy data. Open your package.json and replace the scripts with the following code: "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "start:ios": "react-native run-ios", "start:android": "react-native run-android", "test": "jest" } This will be used to run our application in the respective device. Set Up WatermelonDB We need to add a Babel plugin to convert our decorators, so install it as a dev dependency: npm install -D @babel/plugin-proposal-decorators Create a new file .babelrc in the root of the project: // .babelrc { "presets": ["module:metro-react-native-babel-preset"], "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]] } Now use the following guides for your target environment: iOS Android Open the android folder in Android Studio and sync the project. Otherwise, it will give you an error when running the application for the first time. Do the same if you’re targeting iOS. Before we run the application, we need to link the react-native-gesture handler package, a dependency of react-navigation, and react-native-vector-icons, a dependency of native-base. By default, to keep the binary size of the application small, React Native doesn’t contain all the code to support native features. So whenever we need to use a particular feature, we can use the link command to add the native dependencies. So let’s link our dependencies: react-native link react-native-gesture-handler react-native link react-native-vector-icons Run the application: npm run start:android # or npm run start:ios If you get an error for missing dependencies, run npm i. The code up to here is available under the v0.0 branch. Tutorial As we’ll be creating a database application, a lot of the code will be back-end only, and we won’t be able to see much on the front end. It might seem a long, but have patience and follow the tutorial till the end. You won’t regret it! The WatermelonDB workflow can be categorized into three main parts: Schema: used to define the database table schema. Models: the ORM mapped object. We’ll interact with these throughout our application. Actions: used to perform various CRUD operations on our object/row. We can directly perform an action using a database object or we can define functions in our model to perform these actions. Defining them in models is the better practice, and we’re going to use that only. Let’s get started with our application. Initialize DB Schema and WatermelonDB (v0.1) We’ll define our schema, models and database object in our application. We won’t able to see much in the application, but this is the most important step. Here we’ll check that our application works correctly after defining everything. If anything goes wrong, it will be easy to debug it at this stage. Project Structure Create a new src folder in the root. This will be the root folder for all of our React Native code. The models folder is used for all of our database-related files. It will behave as our DAO (Data Access Object) folder. This is a term used for an interface to some type of database or other persistence mechanism. The components folder will have all of our React components. The screens folder will have all the screens of our application. mkdir src && cd src mkdir models mkdir components mkdir screens Schema Go to the models folder, create a new file schema.js, and use the following code: // schema.js import { appSchema, tableSchema } from "@nozbe/watermelondb"; export const mySchema = appSchema({ version: 2, tables: [ tableSchema({ name: "movies", columns: [ { name: "title", type: "string" }, { name: "poster_image", type: "string" }, { name: "genre", type: "string" }, { name: "description", type: "string" }, { name: "release_date_at", type: "number" } ] }), tableSchema({ name: "reviews", columns: [ { name: "body", type: "string" }, { name: "movie_id", type: "string", isIndexed: true } ] }) ] }); We’ve defined two tables — one for movies, and another for its reviews. The code itself self-explanatory. Both tables have related columns. Note that, as per WatermelonDB’s naming convention, all the IDs end with an _id suffix, and the date field ends with the _at suffix. isIndexed is used to add an index to a column. Indexing makes querying by a column faster, at the slight expense of create/update speed and database size. We’ll be querying all the reviews by movie_id, so we should mark it as indexed. If you want to make frequent queries on any boolean column, you should index it as well. However, you should never index date (_at) columns. Models Create a new file models/Movie.js and paste in this code: // models/Movie.js import { Model } from "@nozbe/watermelondb"; import { field, date, children } from "@nozbe/watermelondb/decorators"; export default class Movie extends Model { static table = "movies"; static associations = { reviews: { type: "has_many", foreignKey: "movie_id" } }; @field("title") title; @field("poster_image") posterImage; @field("genre") genre; @field("description") description; @date("release_date_at") releaseDateAt; @children("reviews") reviews; } Here we’ve mapped each column of the movies table with each variable. Note how we’ve mapped reviews with a movie. We’ve defined it in associations and also used @children instead of @field. Each review will have a movie_id foreign key. These review foreign key values are matched with id in the movie table to link the reviews model to the movie model. For date also, we need to use the @date decorator so that WatermelonDB will give us the Date object instead of a simple number. Now create a new file models/Review.js. This will be used to map each review of a movie. // models/Review.js import { Model } from "@nozbe/watermelondb"; import { field, relation } from "@nozbe/watermelondb/decorators"; export default class Review extends Model { static table = "reviews"; static associations = { movie: { type: "belongs_to", key: "movie_id" } }; @field("body") body; @relation("movies", "movie_id") movie; } We have created all of our required models. We can directly use them to initialize our database, but if we want to add a new model, we again have to make a change where we initialize the database. So to overcome this, create a new file models/index.js and add the following code: // models/index.js import Movie from "./Movie"; import Review from "./Review"; export const dbModels = [Movie, Review]; Thus we only have to make changes in our models folder. This makes our DAO folder more organized. Initialize the Database Now to use our schema and models to initialize our database, open index.js, which should be in the root of our application. Add the code below: // index.js import { AppRegistry } from "react-native"; import App from "./App"; import { name as appName } from "./app.json"; import { Database } from "@nozbe/watermelondb"; import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite"; import { mySchema } from "./src/models/schema"; import { dbModels } from "./src/models/index.js"; // First, create the adapter to the underlying database: const adapter = new SQLiteAdapter({ dbName: "WatermelonDemo", schema: mySchema }); // Then, make a Watermelon database from it! const database = new Database({ adapter, modelClasses: dbModels }); AppRegistry.registerComponent(appName, () => App); We create an adapter using our schema for the underlying database. Then we pass this adapter and our dbModels to create a new database instance. It’s better at this point in time to check whether our application is working fine or not. So run your application and check: npm run start:android # or npm run start:ios We haven’t made any changes in the UI, so the screen will look similar to before if everything worked out. All the code up to this part is under the v0.1 branch. The post Create an Offline-first React Native App Using WatermelonDB appeared first on SitePoint.


SitePoint Premium New Releases: Design Systems, SVG & React Native

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them. Design Systems and Living Styleguides Create structured, efficient and consistent designs with design systems and styleguides. Explore materials, typography, vertical rhythm, color, icons and more. ➤ Read Design Systems and Living Styleguides. Build a Real-time Location Tracking App with React Native and PubNub In this guide, we’re going to use React Native to create real-time location tracking apps. We’ll build two React Native apps — a tracking app and one that’s tracked. ➤ Read Build a Real-time Location Tracking App with React Native and PubNub. Practical SVG From software basics to build tools to optimization, you’ll learn techniques for a solid workflow. Go deeper: create icon systems, explore sizing and animation, and understand when and how to implement fallbacks. Get your images up to speed and look sharp! ➤ Read Practical SVG. Create an Offline-first React Native App Using WatermelonDB In this tutorial we’ll create an offline-first movie search application with a title, poster image, genre, and release date. Each movie will have many reviews. We'll use WatermelonDB to provide the database functionality for our app. ➤ Read Create an Offline-first React Native App Using WatermelonDB. And More to Come… We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin. The post SitePoint Premium New Releases: Design Systems, SVG & React Native appeared first on SitePoint.


Build a Real-time Voting App with Pusher, Node and Bootstrap

In this article, I'll walk you through building a full-stack, real-time Harry Potter house voting web application. Real-time apps usually use WebSockets, a relatively new type of transfer protocol, as opposed to HTTP, which is a single-way communication that happens only when the user requests it. WebSockets allow for persistent communication between the server and the user, and all those users connected with the application, as long as the connection is kept open. A real-time web application is one where information is transmitted (almost) instantaneously between users and the server (and, by extension, between users and other users). This is in contrast with traditional web apps where the client has to ask for information from the server. — Quora Our Harry Potter voting web app will show options (all the four houses) and a chart on the right side that updates itself when a connected user votes. To give you a brief idea of look and feel, the final application is going to look like this: Here's a small preview of how the real-time application works: To make our application real-time, we’re going to use Pusher and WebSockets. Pusher sits as a real-time layer between your servers and your clients. It maintains persistent connections to the clients — over a WebSocket if possible, and falling back to HTTP-based connectivity — so that, as soon as your servers have new data to push to the clients, they can do so instantly via Pusher. Building our Application Let’s create our fresh application using the command npm init. You’ll be interactively asked a few questions on the details of your application. Here's what I had: praveen@praveen.science ➜ Harry-Potter-Pusher $ npm init { "name": "harry-potter-pusher", "version": "1.0.0", "description": "A real-time voting application using Harry Potter's house selection for my article for Pusher.", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/praveenscience/Harry-Potter-Pusher.git" }, "keywords": [ "Harry_Potter", "Pusher", "Voting", "Real_Time", "Web_Application" ], "author": "Praveen Kumar Purushothaman", "license": "ISC", "bugs": { "url": "https://github.com/praveenscience/Harry-Potter-Pusher/issues" }, "homepage": "https://github.com/praveenscience/Harry-Potter-Pusher#readme" } Is this OK? (yes) So, I left most settings with default values. Now it's time to install dependencies. Installing Dependencies We need Express, body-parser, Cross Origin Resource Sharing (CORS), Mongoose and Pusher installed as dependencies. To install everything in a single command, use the following. You can also have a glance of what this command outputs. praveen@praveen.science ➜ Harry-Potter-Pusher $ npm i express body-parser cors pusher mongoose npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself. + pusher@2.1.2 + body-parser@1.18.3 + mongoose@5.2.6 + cors@2.8.4 + express@4.16.3 added 264 packages in 40.000s Requiring Our Modules Since this is an Express application, we need to include express() as the first thing. While doing it, we also need some accompanying modules. So, initially, let’s start with this: const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cors = require("cors"); Creating the Express App Let’s start with building our Express application now. To start with, we need to get the returned object of the express() function assigned to a new variable app: const app = express(); Serving Static Assets Adding the above line after the initial set of includes will initialize our app as an Express application. The next thing we need to do is to set up the static resources. Let’s create a new directory in our current project called public and let’s use Express's static middleware to serve the static files. Inside the directory, let’s create a simple index.html file that says “Hello, World”: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Hello, World</title> </head> <body> Hello, World! </body> </html> To serve the static files, we have a built-in .use() function with express.static() in Express. The syntax is as follows: app.use( express.static( path.join(__dirname, "public") ) ); We also need to use the body parser middleware for getting the HTTP POST content as JSON to access within the req.body. We'll also use urlencoded to get the middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings: app.use( bodyParser.json() ); app.use( bodyParser.urlencoded( { extended: false } ) ); To allow cross-domain requests, we need to enable CORS. Let’s enable the CORS module by using the following code: app.use( cors() ); Now all the initial configuration has been set. All we need to do now is to set a port and listen to the incoming connections on the specific port: const port = 3000; app.listen(port, () => { console.log(`Server started on port ${port}.`); }); Make sure your final app.js looks like this: const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cors = require("cors"); // Create an App. const app = express(); // Serve the static files from public. app.use( express.static( path.join(__dirname, "public") ) ); // Include the body-parser middleware. app.use( bodyParser.json() ); app.use( bodyParser.urlencoded( { extended: false } ) ); // Enable CORS. app.use( cors() ); // Set the port. const port = 3000; // Listen to incoming connections. app.listen(port, () => { console.log(`Server started on port ${port}.`); }); Run the command to start the server: $ npm run dev Open your http://localhost:3000/ on a new tab and see the magic. You should be seeing a new page with “Hello, World”. The post Build a Real-time Voting App with Pusher, Node and Bootstrap appeared first on SitePoint.


State Management in React Native

Managing state is one of the most difficult concepts to grasp while learning React Native, as there are so many ways to do it. There are countless state management libraries on the npm registry — such as Redux — and there are endless libraries built on top of other state management libraries to simplify the original library itself — like Redux Easy. Every week, a new state management library is introduced in React, but the base concepts of maintaining the application state has remained the same since the introduction of React. The most common way to set state in React Native is by using React’s setState() method. We also have the Context API to avoid prop drilling and pass the state down many levels without passing it to individual children in the tree. Recently, Hooks have emerged into React at v16.8.0, which is a new pattern to simplify use of state in React. React Native got it in v0.59. In this tutorial, we’ll learn about what state actually is, and about the setState() method, the Context API and React Hooks. This is the foundation of setting state in React Native. All the libraries are made on top of the above base concepts. So once you know these concepts, understanding a library or creating your own state management library will be easy. What Is a State? Anything that changes over time is known as state. If we had a Counter app, the state would be the counter itself. If we had a to-do app, the list of to-dos would change over time, so this list would be the state. Even an input element is in a sense a state, as it over time as the user types into it. Intro to setState Now that we know what state is, let’s understand how React stores it. Consider a simple counter app: import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => {}} title="Increment" /> <Button onPress={() => {}} title="Decrement" /> </> ) } } In this app, we store our state inside the constructor in an object and assign it to this.state. Remember, state can only be an object. You can’t directly store a number. That’s why we created a counter variable inside an object. In the render method, we destructure the counter property from this.state and render it inside an h1. Note that currently it will only show a static value (0). You can also write your state outside of the constructor as follows: import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => {}} title="Increment" /> <Button onPress={() => {}} title="Decrement" /> </> ) } } Now let’s suppose we want the + and - button to work. We must write some code inside their respective onPress handlers: import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => { this.setState({ counter: counter + 1 }) }} title="Increment" /> <Button onPress={() => { this.setState({ counter: counter - 1 }) }} title="Decrement" /> </> ) } } Now when we click the + and - buttons, React re-renders the component. This is because the setState() method was used. The setState() method re-renders the part of the tree that has changed. In this case, it re-renders the h1. So if we click on +, it increments the counter by 1. If we click on -, it decrements the counter by 1. Remember that you can’t change the state directly by changing this.state; doing this.state = counter + 1 won’t work. Also, state changes are asynchronous operations, which means if you read this.state immediately after calling this.setState, it won’t reflect recent changes. This is where we use “function as a callback” syntax for setState(), as follows: import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => { this.setState(prevState => ({ counter: prevState.counter + 1 })) }} title="Increment" /> <Button onPress={() => { this.setState(prevState => ({ counter: prevState.counter - 1 })) }} title="Decrement" /> </> ) } } The “function as a callback” syntax provides the recent state — in this case prevState — as a parameter to setState() method. This way we get the recent changes to state. What are Hooks? Hooks are a new addition to React v16.8. Earlier, you could only use state by making a class component. You couldn’t use state in a functional component itself. With the addition of Hooks, you can use state in functional component itself. Let’s convert our above Counter class component to a Counter functional component and use React Hooks: import React from 'react' import { Text, Button } from 'react-native' const Counter = () => { const [ counter, setCounter ] = React.useState(0) return ( <> <Text>{counter}</Text> <Button onPress={() => { setCounter(counter + 1 ) }} title="Increment" /> <Button onPress={() => { setCounter(counter - 1 ) }} title="Decrement" /> </> ) } Notice that we’ve reduced our Class component from 18 to just 12 lines of code. Also, the code is much easier to read. Let’s review the above code. Firstly, we use React’s built-in useState method. useState can be of any type — like a number, a string, an array, a boolean, an object, or any type of data — unlike setState(), which can only have an object. In our counter example, it takes a number and returns an array with two values. The first value in the array is the current state value. So counter is 0 currently. The second value in the array is the function that lets you update the state value. In our onPress, we can then update counter using setCounter directly. Thus our increment function becomes setCounter(counter + 1 ) and our decrement function becomes setCounter(counter - 1). React has many built-in Hooks, like useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect and useDebugValue — which you can find more info about in the React Hooks docs. Additionally, we can build our own Custom Hooks. There are two rules to follow when building or using Hooks: Only Call Hooks at the Top Level. Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. Only Call Hooks from React Functions. Don’t call Hooks from regular JavaScript functions. Instead, you can either call Hooks from React functional components or call Hooks from custom Hooks. By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code. Hooks are really simple to understand, and they’re helpful when adding state to a functional component. The post State Management in React Native appeared first on SitePoint.


How to Redesign Unsplash Using Styled Components

Writing future-proof CSS is hard. Conflicting classnames, specificity issues, and so on, come up when you have to write and maintain thousands of lines of CSS. To get rid of the aforementioned issues, Styled Components was created. Styled Components makes it easy to write your CSS in JS and makes sure there are no conflicting classnames or specificity issues with multiple other benefits. This makes writing CSS a joy. In this tutorial, we’ll explore what CSS in JS is, the pros and cons of styled-components, and finally, we’ll redesign Unsplash using Styled Components. After completing this tutorial, you should be able to quickly get up and running with Styled Components. Note: Styled Components was specifically built with React in mind, so you have to be using React to use Styled Components. Prerequisites For this tutorial, you need a basic knowledge of React. Throughout the course of this tutorial we’ll be using yarn. If you don’t have yarn already installed, then install it from here. To make sure we’re on the same page, these are the versions used in this tutorial: Node 12.6.0 npx 6.4.1 yarn 1.17.3 Evolution of CSS Before CSS-in-JS was created, the most common way to style web apps was to write CSS in a separate file and link it from the HTML. But this caused trouble in big teams. Everyone has their own way of writing CSS. This caused specificity issues and led to everyone using !important. Then came Sass. Sass is an extension of CSS that allows us to use things like variables, nested rules, inline imports and more. It also helps to keep things organized and allows us to create stylesheets faster. Even though Sass might be thought of as an improvement over CSS, it arguably causes more harm than good without certain systems put in place. Later, BEM came in. BEM is a methodology that lets us reduce specificity issues by making us write unique classnames. BEM does solve the specificity problem, but it makes the HTML more verbose. Classnames can become unnecessarily long, and it's hard to come up with unique classnames when you have a huge web app. After that, CSS Modules were born. CSS Modules solved what neither Sass nor BEM could — the problem of unique classnames — by tooling rather than relying on the name given by a developer, which in turn solved specificity issues. CSS Modules gained a huge popularity in the React ecosystem, paving the way for projects like glamor. The only problem with all these new solutions was that developers were made to learn new syntaxes. What if we could write CSS exactly how we write it in a .css file but in JS? And thus styled-components came into existence. Styled Components uses Template Literals, an ES6 feature. Template literals are string literals allowing embedded expressions. They allow for multi-line strings and string interpolation features with them. The main selling point of Styled Components is that it allows us to write exact CSS in JS. Styled Components has a lot of benefits. Some of the pros and cons of Styled Components are listed below. Pros There are lots of advantages to using Styled Components. Injecting Critical CSS into the DOM Styled Components only injects critical CSS on the page. This means users only download CSS needed for that particular page and nothing else. This loads the web page faster. Smaller CSS bundle per page As it only injects styles that are used in the components on the page, bundle size is considerably smaller. You only load the CSS you need, instead of excessive stylesheets, normalizers, responsiveness, etc. Automatic Vendor Prefixing Styled Components allows you to write your CSS and it automatically vendor prefixes according to the latest standard. Remove unused CSS With Styled Components, it's easier to remove unused CSS or dead code, as the styles are colocated with the component. This also impacts on reducing bundle size. Theming is easy Styled Components makes it really easy to theme a React applications. You can even have multiple themes in your applications and yet easily maintain them. Reduces the number of HTTP requests Since there are no CSS files for resets, normalizers, and responsiveness, the number of HTTP requests are considerably reduced. Unique Classnames Styled Components generates unique classnames every time a build step takes place. This allows avoiding naming collisions or specificity issues. No more having global conflicts and being forced to resolve them with !important tags. Maintenance is easy Styled Components allows you to colocate styles with the component. This allows for painless maintenance. You know exactly which style is affecting your component, unlike in a big CSS file. Cons Of course, nothing's perfect. Let's look at some downsides associated with Styled Components. Unable to Cache Stylesheets Generally, a web browser caches .css files when a user visits a website for the next visit, so it doesn't have to download the same .css file again. But with styled-components, the styles are loaded in the DOM using the <style> tag. Thus, they can’t be cached and every time user has to request styles when they visit your website. React specific Styled Components was made with React in mind. Thus, it’s React specific. If you use any other framework, then you can’t use Styled Components. However, there’s an alternative very similar to styled-components known as emotion which is framework agnostic. The post How to Redesign Unsplash Using Styled Components appeared first on SitePoint.


4 Key Principles to Remember When Building B2B Ecommerce Websites

This article was created in partnership with StudioWorks. Thank you for supporting the partners who make SitePoint possible. B2B ecommerce businesses are currently facing a bit of a boom. Forrester estimates that B2B ecommerce revenues will reach $1.8 trillion in the US in the next four years. And a recent BigCommerce study found that 41% of B2B retailers predict their online sales to increase more than 25% by the end of the year. So if you’re building a B2B ecommerce storefront to capitalize on this boom, it’s important that you take the time to ensure that the website has all the right functionality to receive and fulfill orders, and to deliver a great shopping experience to your buyers. In this post, we’ll take a look at some of the key principles you’ll need to keep in mind when tackling a B2B ecommerce website build. But before we begin, let’s put everything into a bit of context. Key Differences Between B2C and B2B Ecommerce Sites B2B ecommerce companies, of course, provide the goods and services that other companies need to operate and grow. In the ecommerce space, when we refer to a B2B company, we’re generally talking about firms that sell physical goods on a wholesale basis, but other types of B2B companies have been known to get into the ecommerce game. For example, industrial suppliers or consultancy service providers are generally B2B companies, and they may or may not offer online purchasing options too. B2C companies, on the other hand, sell their products and services direct to individual customers. Image source Currently, the B2B ecommerce opportunity is huge compared to B2C ecommerce, which has become harder to crack due to high levels of competition and low barriers to entry. B2B buyers are becoming increasingly interested in making purchases online. Sellers, meanwhile, are only starting to make it possible. But just because the demand is there doesn’t mean corporate buyers are expecting the same type of experiences from B2B ecommerce that they get on Amazon. Here are a few key differences between B2B and B2C, when it comes to ecommerce interfaces and customer experiences. Breadth of audience One major difference between B2B and B2C is the scale of their target audience. B2B sites deal with buyers who have simple, targeted profiles such as CTOs at tech startups. On the flip side, B2C sites have a broader group of people to cater to — for instance, moms with toddlers or millennials who are into sneakers. For this reason, B2B ecommerce sites typically have a different purchasing user flow which involves more personalization. Average price point Most B2C ecommerce sites sell to hundreds of thousands of customers because their products typically sell at a lower price point. On the other hand, B2B sites may have less than 100 customers. B2B ecommerce sites often use quote builders and set up different technology to be able to accept and process larger orders. For example, this may include options for recurring payments, bulk discounts, and shipping. The decision-making process B2C buying decisions are made fairly quickly, as they’re generally less rational and more based on impulse. Lower pricing points make this possible. In B2B decisions, the purchasing manager may have to get approval from senior executives, finance, marketing, and legal departments before placing an order. To streamline the decision-making process, B2B ecommerce site owners offer tailored pricing to buyers. They also set up customer accounts to make it easy for buyers to fill out orders and complete transactions. With the above in mind, let’s take a closer look at some of the important principles to guide you as you build your next B2B ecommerce website. 1. Integrate with an ERP Solution As a B2B company, you’ll be able to significantly increase productivity by integrating an ERP solution with your ecommerce site. The key benefit is that your inventory levels will automatically update in two places. Inventory availability figures can appear on the front end of the site as goods are added to inventory, giving customers a better shopping experience. Plus, with access to ERP data on the back end, you can enable your staff to easily meet orders and forecast product demand. Another key benefit of integrating an ERP solution is that you won’t need to hire additional workers in case product demand goes up. Here are some of the most common ERP integration patterns: Migration. Data migration ERP refers to the movement of a particular set of data between two systems at a specific point in time. The migration can either be on an as-needed basis through an API or on command by setting the configuration parameters to pass into the API calls. Broadcast. The broadcast ERP integration pattern involves the transfer of data from one source system to multiple destination systems in real time. Broadcast systems help move data quickly between systems and keep multiple systems up to date across time. Aggregation. This ERP pattern receives data from multiple systems and stores it into only one system. It eliminates the need to regularly run multiple migrations, which removes the risk associated with data synchronization and accuracy. Bi-directional synchronization. Bi-directional sync ERP integration is useful in situations where different systems are required to perform different functions in the same data set. Correlation. Correlation is similar to bi-directional ERP integration. The difference is that the former synchronizes objects only if they’re present in both systems. Image source BigCommerce offers a number of ERP integrations, including Brightpearl, Stitch Labs, NetSuite ERP Connector by Patchworks, and Acumatica Cloud ERP by Kensium via the eBridge Connections systems integrator. The post 4 Key Principles to Remember When Building B2B Ecommerce Websites appeared first on SitePoint.


25+ JavaScript Shorthand Coding Techniques

This really is a must read for any JavaScript developer. I have written this guide to shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on, I have included the longhand versions to give some coding perspective. August 26th, 2019: This article was updated to add new shorthand tips based on the latest specifications. If you want to learn more about ES6 and beyond, sign up for SitePoint Premium and check out our extensive library of modern JavaScript resources. 1. The Ternary Operator This is a great code saver when you want to write an if..else statement in just one line. Longhand: const x = 20; let answer; if (x > 10) { answer = "greater than 10"; } else { answer = "less than 10"; } Shorthand: const answer = x > 10 ? "greater than 10" : "less than 10"; You can also nest your if statement like this: const answer = x > 10 ? "greater than 10" : x < 5 ? "less than 5" : "between 5 and 10"; 2. Short-circuit Evaluation Shorthand When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty. You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation. Longhand: if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; } Shorthand: const variable2 = variable1 || 'new'; Don’t believe me? Test it yourself (paste the following code in es6console): let variable1; let variable2 = variable1 || 'bar'; console.log(variable2 === 'bar'); // prints true variable1 = 'foo'; variable2 = variable1 || 'bar'; console.log(variable2); // prints foo Do note that if you set variable1 to false or 0, the value bar will be assigned. 3. Declaring Variables Shorthand It's good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time. Longhand: let x; let y; let z = 3; Shorthand: let x, y, z=3; 4. If Presence Shorthand This might be trivial, but worth a mention. When doing “if checks”, assignment operators can sometimes be omitted. Longhand: if (likeJavaScript === true) Shorthand: if (likeJavaScript) Note: these two examples are not exactly equal, as the shorthand check will pass as long as likeJavaScript is a truthy value. Here is another example. If a is NOT equal to true, then do something. Longhand: let a; if ( a !== true ) { // do something... } Shorthand: let a; if ( !a ) { // do something... } 5. JavaScript For Loop Shorthand This little tip is really useful if you want plain JavaScript and don't want to rely on external libraries such as jQuery or lodash. Longhand: const fruits = ['mango', 'peach', 'banana']; for (let i = 0; i < fruits.length; i++) Shorthand: for (let fruit of fruits) If you just wanted to access the index, do: for (let index in fruits) This also works if you want to access keys in a literal object: const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'} for (let key in obj) console.log(key) // output: continent, country, city Shorthand for Array.forEach: function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [2, 5, 9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = 9 6. Short-circuit Evaluation Instead of writing six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code. Longhand: let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; } Shorthand: const dbHost = process.env.DB_HOST || 'localhost'; 7. Decimal Base Exponents You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e7 essentially means 1 followed by 7 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 10,000,000. Longhand: for (let i = 0; i < 10000; i++) {} Shorthand: for (let i = 0; i < 1e7; i++) {} // All the below will evaluate to true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000; 8. Object Property Shorthand Defining object literals in JavaScript makes life much easier. ES6 provides an even easier way of assigning properties to objects. If the variable name is the same as the object key, you can take advantage of the shorthand notation. The post 25+ JavaScript Shorthand Coding Techniques appeared first on SitePoint.


SitePoint Premium New Releases: Form Design + Cloning Tinder

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them. Form Design Patterns On first glance, forms are simple to learn. But when we consider the journeys we need to design, the users we need to design for, the browsers and devices being used; and ensuring that the result is simple and inclusive, form design becomes a far more interesting and bigger challenge. ➤ Read Form Design Patterns. Cloning Tinder Using React Native Elements and Expo In this tutorial, we’ll be cloning the most famous dating app, Tinder. We’ll then learn about a UI framework called React Native Elements, which makes styling React Native apps easy. Since this is just going to be a layout tutorial, we’ll be using Expo, as it makes setting things up easy. ➤ Read Cloning Tinder Using React Native Elements and Expo. And More to Come… We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin. The post SitePoint Premium New Releases: Form Design + Cloning Tinder appeared first on SitePoint.


How to Use Windows Subsystem for Linux 2 and Windows Terminal

In this article, you’ll learn how you can set up and run a local Linux shell interface in Windows without using a virtual machine. This not like using terminals such as Git Bash or cmder that have a subset of UNIX tools added to $PATH. This is actually like running a full Linux kernel on Windows that can execute native Linux applications. That's pretty awesome, isn't it? If you’re an experienced developer, you already know that Linux is the best platform on which to build and run server-based solutions using open-source technologies. While it’s possible to run the same on Windows, the experience is not as great. The majority of cloud hosting companies offer Linux to clients to run their server solutions in a stable environment. To ensure software works flawlessly on the server machine just like on the local development machine, you need to run identical platforms. Otherwise, you may run into configuration issues. When working with open-source technologies to build a project, you may encounter a dependency that runs great on Linux but isn’t fully supported on Windows. As a result, Windows will be required to perform one of the following tasks in order to contribute to the project: Dual Boot Windows and Linux (switch to Linux to contribute code) Run a Linux virtual machine using a platform such as Vagrant, VirtualBox, VMWare etc. Run the project application inside a Docker container All the above solutions require several minutes from launch to have a full Linux interface running. With the new Windows Subsystem for Linux version 2 (WSL2), it takes a second or less to access the full Linux shell. This means you can now work on Linux-based projects inside Windows with speed. Let's look into how we can set up one in a local machine. Installing Ubuntu in Windows First, you'll need to be running the latest version of Windows. In my case, it's build 1903. Once you've confirmed this, you'll need to activate the Windows Subsystem for Linux feature. Simply go to Control-Panel -> Programs -> Turn Windows feature on or off. Look for "Windows Subsystem for Linux" and mark the checkbox. Give Windows a minute or two to activate the feature. Once it's done, click the restart machine button that appears next. Next, go to the Windows Store and install Ubuntu. The first Ubuntu option will install the latest versions. Other Ubuntu options allow you to install an older supported version. Once the installation is complete, you'll need to launch it from the menu. Since this is the first time, you’ll need to wait for the Ubuntu image to be downloaded and installed on your machine. This is a one-time step. The next time you launch, you’ll access the Linux Shell right away. Once the image installation is complete, you’ll be prompted to create a new root user account inside this shell: After you’ve created your credentials, feel free to type any Linux command to confirm you’re truly accessing a native Linux shell: You’ll be pleased to note that git, python3, ssh, vim, nano, curl, wget and many other popular tools are available out of the box. In a later section, we'll use sudo apt-get command to install more frameworks. First, let's look at several ways we can access this new Linux shell terminal interface. It's probably a good idea to upgrade currently installed packages: $ sudo apt-get update && sudo ap-get upgrade Accessing Linux Shell Interface The are several interesting ways of accessing the Linux shell interface. Go to Windows Menu Start > type "Ubuntu". You can pin it to Start for quicker access Open Command Prompt or Windows PowerShell and execute the command bash In Windows explorer, SHIFT + right-mouse click a folder to open a special context menu. Click Open Linux shell here. In Windows explorer, navigate to any folder you desire, then in the address bar type wsl, then press enter. In Visual Studio Code, change the default terminal to wsl. If you come across new ways, please let me know. Let's set up Node.js in the following section. The post How to Use Windows Subsystem for Linux 2 and Windows Terminal appeared first on SitePoint.


These Are the Best Developer Tools & Services

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible. As you've learned through experience, there's much involved in trying to find the right developers' tools or services for the task at hand. It's a challenge. More and more software products and services are appearing on the market. But, every year it doesn't get any easier. This can be especially true in some cases. One case is where app developers have been trying to bridge the gap between software development and operations. As you will see, open-source solutions go a long way toward resolving some of these problems. There are services that developers can use and that way can save them both time and money. That's the case with the 6 products and services described below. The post These Are the Best Developer Tools & Services appeared first on SitePoint.