emGee Software Solutions Custom Database Applications

Share this

Web Design

10 Best WordPress Facebook Widgets (and 5 Free Plugins)

Tuts+ Code - Web Development - Thu, 05/28/2020 - 10:53

In order to run a successful business, you need to promote and advertise your company wherever your audience's attention is. Adding premium WordPress Facebook widgets to your website will help you connect with your customers. 

One of the many premium WordPress Facebook widgets available on CodeCanyon

Facebook allows you to promote your business through text, images, and videos all of which are necessary to promote your business successfully. At CodeCanyon, you will be able to choose from all the premium Facebook widgets available and they will allow you to display all of these elements on your website.  

Don't miss out on this opportunity to improve your business through premium Facebook widgets for WordPress!

The Best WordPress Facebook Widgets on CodeCanyon

Discover CodeCanyon's extensive library of the best WordPress widgets and plugins ever created. With a cheap one-time payment, you can purchase these high-quality plugins and widgets and grow your business through Facebook. 

Here are a few of the best Facebook WordPress widget plugins available on CodeCanyon for 2020.

These feature-rich WordPress widgets for Facebook will assist you in connecting with your target audiences in one of the most popular social media platforms on the planet. With the premium widgets offered on CodeCanyon, you will be able to:

  • display your Facebook pages feed 
  • customize the feed to fit with your website's theme
  • add Facebook chat widgets
  • grow your Facebook following through customizable Like buttons

Add a high-quality WordPress Facebook widget to your website today!

Top 10 WordPress Facebook Widgets (From CodeCanyon for 2020) 1. Facebook Feed

The Facebook Feed WordPress widget is essentially four Facebook plugins in one.

With it, you can display your Facebook Posts Feed, Image Gallery, Video Gallery, and Events Calendar.

Features include:

  • fully responsive and ready for any screen size
  • includes Like and Share actions
  • supports WPBakery (Visual Composer)
  • and more

Facebook Feed is a great way to get your Facebook content on your website.

2. Top Social Stories

You can add more than just your Facebook feed with Top Social Stories: it lets you easily track daily interactions on Facebook, Twitter, and more.

Features include:

  • display top stories based on most shares
  • export data to custom fields
  • works for custom post types
  • fully customizable
  • and more

Whether you need it solely for Facebook or you want to add other social media feeds into the mix, Top Social Stories is a great way to display social media posts.

3. Facebook Likebox Slider for WordPress

With Facebook Likebox Slider you can easily get more shares, traffic, and fans. With this widgets 3-click configuration, you can easily get up and running in no time. Not only can this widget be used for Facebook, but it supports all other popular social media platforms as well! Here are a few notable features of this widget. 

  • iPad, iPhone, other mobile devices support
  • very fast loading
  • language selection
  • live preview
4. Facebook Reviews Pro

Displaying reviews to your website visitors will help build trust. This trust is essential for making converting visitors into customers. Facebook reviews pro allows you to display your Facebook page's reviews and trust badges on your website, so this trust can be built. Here are a few notable functions of this widget.

  • filter reviews display
  • pagination
  • integrates with WPBakery
  • 24/7 premium support
  • no coding required
5. Facebook Recent Comments Widget

The Facebook Recent Comments Widget for WordPress brings the comment activity from your Facebook page and brings it to your WordPress widget area.

It's SEO friendly and super easy to use!

You can:

  • receive email notifications for Facebook comment box comments
  • manually or automatically approve comments to display
  • and customize the widget

Facebook Recent Comments Widget for WordPress is an easy way to display the latest Facebook comments on your WordPress-powered website.

6. Facebook Traffic Pop for WordPress

The Facebook Traffic Pop plugin for WordPress will allow you to have your users like your pages through a visually appealing popup. This highly customizable popup can fit right into the theme of your website and is guaranteed to boost your Facebook page's presence and popularity. Here are a few features that this plugin includes:

  • multi-theme support
  • mobile responsive
  • locks page functionality
  • quick and easy configuration
7. Social Stream for WordPress with Carousel

Social Stream for WordPress with Carousel is a viable option whether you're interested in only displaying Facebook content or content from multiple social media networks at one time.

With Social Stream, you can funnel all your social media streams to your WordPress-powered website in style.

There are several display options included with this social media carousel:

  • combine multiple social media feeds into one
  • 3 different styles and customizable colors
  • over 60 animation effects
  • responsive feed layout
  • and more

If you're interested in mixing in other social media streams along with your Facebook feed, Social Stream for WordPress with Carousel may be exactly what you're looking for.

8. Facebook Events Calendar

Display your Facebook events using a widget or shortcode with the Facebook Events Calendar.

This full-featured solution not only looks great, but has some great features as well.

Features include:

  • full and compact layouts
  • quick-view popups for each day
  • calendar and list views
  • and more

The Facebook Events Calendar is easy to use and one of the best ways to display your Facebook Page public events on your website. No need to maintain two calendars any more!

9. Facebook Chat

Facebook Chat  is the fastest way for your clients to reach you and get their questions answered. This chat widget gives you a direct line of communication to your customers and potential customers 24/7. 

The chat can be customized to be shown on specific pages or to specific users. Keep a line of communication open with your website visitors with this powerful chat widget. 

10. Facebook Messenger Bulksender

The Messenger Bulksender not only allows you to send bulk messages to your customer base, but it allows you to use auto-reply to trigger the user's comments on your Facebook page posts. Here are a few notable features of this messenger widget:

  • unlimited ad creation
  • send messages to customers inboxes
  • shortcut for bulk message sending
  • customizable audience segmentation

Now that we have gone over some of the best premium Facebook widgets available, let's go over a few free options. 

5 Free Facebook Widgets and Plugins for Download in 2020

By purchasing a premium Facebook WordPress widget, you will receive the most advanced set of features and functionality. The number of features that these widgets will have and the overall user experience will be much higher with a premium widget. 

If your budget does not allow you to afford these premium Facebook widgets, there are plenty of free alternatives for you to check out.

Here is a list of five of the best free WordPress Facebook widgets and plugins available.

1. Simple Like Page

Simple Like Page is just that, simple. Give your website visitors a chance to connect with your Facebook page by offering a like button on your website. This simple plugin is sure to be help boost your Facebook audience.

2. FB Page Promoter Lightbox

FB Page Promoter Lightbox allows you to display a highly-configurable modal to convert your website traffic into fans. With this plugin, you can display the Facebook lightbox to your visitors on a schedule. 

3. Easy Social Post Feed

This beginner-friendly plugin will allow you to not only display a custom Facebook feed, but also a custom Instagram feed. With the custom Facebook feed, you can add posts, links, photos, videos, and events. This plugin is an all in one solution for your Facebook needs!

4. Smash Balloon Social Post Feed

Display completely customizable, responsive, and search engine friendly Facebook feeds on your website with this plugin. You can include multiple Facebook feeds from any public Facebook page and customize their appearance to fit the theme of your website. 

5. WP2Social Auto Publish

WP2Social Auto Publish is one handy plugin. You can publish posts automatically from your blog to Facebook. The plugin supports filtering posts based on custom post-types as well as categories.

How to Add a Facebook Chat to Your Website Using WordPress Facebook Chat Widget

Now that we have gone over the best premium and free WordPress Facebook widget plugins available I am going to show you just how easy it is to implement them into your website. 

The Facebook Chat widget is an incredibly powerful tool that can be used to keep in contact with your website audience around the clock. In this short tutorial, I going to show you how you can connect your business's Facebook page to the chat widget and display the chat in the bottom right-hand corner of your website. 

Once you have installed the Facebook Chat widget, head on over to WP Dashboard > Facebook Chat. This will open up the chat widget creator. Click the Create Widget button and type in "Facebook Chat" in the text field for the name of the widget. 

Next, we will connect our Facebook page to the chat so we can receive messages from the chat. Click on the Connect to Facebook button and you will be asked to log in to your Facebook account. From there, you can select the page that you want to be linked with the chat widget. Click the Connect button and your page will now be connected to the chat. 

Finally, we would like to make a few changes to the text and styling of the chat widget that is on the website. We will choose the Chat Bubble menu item and choose the mail icon. Next, we will select the Welcome Message menu item and change the text to say, "Thanks for stopping on by! Feel free to send me a message!"

Now that we have connected our Facebook page and edited the styling and text of the chat, it is time to add it to our website. Click the Save and Exit button at the bottom of the chat editor. This will take you to an overview of all of your chat widgets and display the shortcodes for each widget. Copy the shortcode of the Facebook Chat widget and paste it to the visual editor of the post or page that you would the chat to be displayed on. That is it! You have now successfully added a Facebook chat to your WordPress website. 

Install a WordPress Facebook Widget Now! 

It's just a matter of comparing prices, options, and reading a few user reviews before finding the right Facebook widget. Facebook is a powerful social media platform that should not be overlooked. Integrating it into your website can make a big difference.

If you are looking to gain more exposure for your business, then add a premium Facebook widget from CodeCanyon to your WordPress website.

The plugins available will allow you to add Facebook messengers, feeds, images, videos, and like buttons to your website and customize them to fit the theme of your website. 

If the plugins listed in this article did not seem to suit your needs, you can always browse CodeCanyon for more high-quality Facebook widgets and plugins. 

Also, don't miss out on the thousands of other high-quality WordPress plugins on CodeCanyon that can help you grow your business. Have a look through this massive collection of plugins, and you'll find helpful plugins in all different types of categories from marketing to eCommerce to social media.

CodeCanyon has the tools necessary to help your business succeed so act now!

Other Ways to Connect WordPress and Facebook

If you want to learn more about connecting WordPress and Facebook, or want to discover more Facebook plugins for WordPress, check out our other posts here on Envato Tuts+.


Categories: Web Design

17 Most Useful PHP Scripts (and 5 Great Free Scripts)

Tuts+ Code - Web Development - Wed, 05/27/2020 - 13:31

Whether you need to create a dating website, add a shopping cart to your eCommerce store, or launch a marketing campaign, there is a PHP script that is right for you. Add a new set of features and functionality to your website with these scripts and create a more robust platform for your customers. 

Today's website viewers are accustomed to using modern, simple, and fully functional websites. Anything less than this will make the site they are using seem unprofessional in their eyes. This makes it a must for you to have a website that can be competitive with today's websites. CodeCanyon allows you to choose from some of the most high-quality PHP scripts available on the web that you can add to your website.

The Best PHP Scripts on CodeCanyon

Discover over 4,000 of the best PHP scripts ever created on Envato Market's CodeCanyon. With a cheap one-time payment, you can purchase one of these high-quality PHP scripts. 

Here are a few of the best PHP scripts available on CodeCanyon for 2020.

PHP scripts are very versatile and can be used to solve any of your business's problems. 

By taking advantage of the premium PHP scripts available on CodeCanyon, you will have access to professionally created scripts that will make a difference on your website. 

Here are just a few of the features that can be added to your website with these scripts:

  • support chats
  • marketplaces
  • course management
  • booking systems
  • restaurant ordering
Top 17 PHP Scripts (From CodeCanyon for 2020)

To help you with your search for the best PHP scripts your business, I've collected 17 of the best-selling PHP scripts on CodeCanyon:

1. MailWizz

MailWizz will give you complete control over your email marketing. You can even create your own email service provider service for your customers. This is all made possible by the self-hosting of the MailWizz software. You no longer need to pay monthly subscriptions to other email service providers with this complete email management software. 

Here are a few notable features of MailWizz:

  • comprehensive overview dashboard
  • autoresponder and campaign emails
  • custom user groups
  • email list manager

View the live preview of MailWizz here!

Later on in this post, I'll share some of the benefits of this plugin in depth.

2. Academy Learning Management System

Academy is a marketplace PHP script for online learning. Students and teachers are can join the system and create a classroom environment through a course-based system. Teachers can create as many courses, video lessons, and documents as they want and have students enroll in them. You can easily sell your online courses and start a profitable teaching business with Academy. 

View the live preview of this marketplace PHP script and see just how powerful Academy is!

3. Foodomaa

Foodomaa is a multi-restaurant food ordering and membership system. You can expect to find an admin dashboard, restaurant management system, delivery system, and a fully-featured web application. Here a few highlights of this PHP script:

  • GPS-based dynamic delivery charges system
  • complete product customization 
  • multiple order placing functionality
  • social login and OTP registration
  • restaurant commission and payout system
4. Perfex

Perfex CRM is a complete customer relationship management software that will work for any business or freelancer. It has a powerful support system that helps you track and resolve issues quickly through the software's integrated ticket system. 

Here are a few notable features:

  • powerful project management feature
  • link tasks to many Perfex CRM features and stay organized.
  • professional-looking estimates and invoices
  • time tracking for customers and staff members
  • built-in surveys

If you ever encounter any issues, the Perfex CRM has outstanding support that is available to help you with any issues you may have. 

5. WoWonder

WoWonder is a PHP Social Network Script that allows you to start your own social media website. This PHP script is the most complete social media script and even has built-in features to allow users to advertise on your site based on a CPC and CPM pricing model. If you are looking to create any type of social media network, then this script is for you.

Here are a few notable features: 

  • friends & follow system
  • home with newsfeed
  • user timeline
  • social videos support

View the live preview of this social network script now!

6. All in One Video Downloader Script

This video downloader script allows you to download from 25+ popular websites with one click. You can download videos in multiple formats including MP4, M4A, 3GP, WEBM, MP3, and JPG. This script is incredibly helpful if you need to consistently download videos. You can see this downloading script in action by viewing the live preview.

7. Karenderia Multiple Restaurant System

Karenderia is a food ordering and restaurant membership system. It allows you to add restaurants into the system based on your user's location and allows them to place an order that can be delivered to their home. 

Here is what you can expect to see in this PHP script:

  • easy to manage food items
  • Paypal and credit card payment gateway integrations
  • sponsored listings
  • detailed sales reports and graphs

Take a look at how your restaurant ordering website can look with Karenderia. 

8. TikTok Video and Music Downloader

TikTok Video Downloader lets you download an image or video post from TikTok from a URL. A video link will automatically be generated with this script. This can be very useful if you are looking to create videos from other TikTok videos. TikTok doesn't give you this feature and this script helps you save time from having to screen record and screen capture images and videos. Try this downloader for free!

9. XeroChat

XeroChat is a multichannel marketing application that can help your business grow. It offers a wide range of tools including a messenger chatbot, Facebook comment bot, social media posting, email marketing, and much more. This powerful tool also comes with a built-in eCommerce platform for selling products inside Facebook Messenger. 

The resources available in this PHP script allow you to do employ analytical marketing to make the most informed decisions that you possibly can. If you are serious about your marketing campaigns, then this is a must-have. 

10. Laravel eCommerce

Laravel eCommerce is an all in one solution for your eCommerce needs. You can save hundreds of hours from having to develop eCommerce stores from scratch with this script. Within ten minutes, you can get up and running with the demo content on your own website. Worried about having to pay for future updates of Laravel eCommerce? Don't be! You get a lifetime worth of updates with your initial purchase. 

Check out the live preview of Laravel eCommerce.

11. QuickDate

Interested in starting your own dating website? QuickDate will give you the tools to get up and running with your own dating platform. All the standard features such as profile creation and messaging are included in this script. 

Additional features include:

  • powerful admin panel
  • credit system for messages, gifts, and likes
  • SEO friendly 
  • WoWonder integration
12. Acelle Email Marketing Web Application

Acelle Mail is another self-hosted email marketing web application similar to MailWizz. You will be able to send high-volume marketing emails via your own server or through other SMTP providers and you will not have to pay a monthly subscription fee. Acelle is also designed to be a SaaS platform that allows you to manage and sell your email services. Take a look at how Acelle can work for you.

13. FleetCart

Need help starting an eCommerce site but don't know where to start? FleetCart is a fully functional Laravel eCommerce system that has a powerful admin panel for managing products, categories, coupons, and much more. 

Here are a few notable features of this eCommerce system: 

  • fully responsive design
  • 8 themes to choose from
  • scheduled currency rate updating
  • sales analytics charts
  • guest checkout
14. eClass Learning Management System

The eClass learning management system allows teachers all around the world to deliver classes and spread information. With eClass, students can buy your online courses quickly and easily. 

The platform gives you the ability to upload images, videos, PDFs and zip files for your customers to access and use. Payment gateways such as PayPal and Stripe are integrated into the system to allow for seamless transactions. Have a course to sell? Get up and running with eClass right now!

15. Active eCommerce CMS

Active eCommerce is a fully-featured eCommerce and marketplace platform that can be adapted to fit any size business. All major payment gateways are integrated into the store as well as a dynamic wallet system that lets users shop from their wallet balance. 

One very useful feature that is included is an order tracking system that allows your customers to see where their deliveries are. If you need a marketplace that works seamlessly for buyers and sellers, this is the PHP script for you.

16. Varient News & Magazine Script

Varient is a multi-purpose news & magazine script that has a modern and minimalist design. The comprehensive admin panel grants you complete control over all the content on the website. 

Here is what you can expect from this news & magazine script:

  • multilingual system
  • SEO optimized
  • RSS aggregator and cache system
  • responsive ad spaces
  • article, video, and post options

View the live preview of Varient to see what your website could look like.

17. SocialProofo

Take your marketing to the next level with this unique PHP script. SocialProofo includes plugins and pop-ups to create social proof and a fear of missing out (FOMO). The type of campaigns that you can run with SocialProofo will cost much more than the one time purchase for the script making this a bargain. To see exactly how this script works, view the live demo.

5 Free PHP scripts for Download in 2020

Without a doubt, paid PHP scripts give you the most complete set of features and tools. However, there are a lot of great free PHP scripts that might just do what you need.

If you are running on a limited budget, then check out 5 of the best free PHP scripts available below. 

1. AdminPanel

AdminPanel is a free PHP script that grants access to the control features of your site by creating dynamic and data grid pages. You can organize all of your site's content from this admin panel. 

2. Shopping Cart

This is a powerful open-source PHP solution for anyone who needs a shopping cart in their online store. The script has all of the basic features of adding products to the cart and viewing and adding and removing the collection of products in the cart. 

3. Guest Book

This free PHP script is ideal if you want to give your website viewers an opportunity to give their opinions about your website. You don't even need a MySQL database to run this script. Visitors can post private guestbook messages that only you can read. 

4. TreeMenu  

This free script will generate a multilevel tree menu control that will help you organize the content of your website. Tree menu is one of the most widely used navigation controls and can make a great addition to your website from a functionality standpoint. 

5. Business Directory

Business Directory enables you to add categories and associate your added businesses to these categories. You can add basic contact info, business descriptions, websites, and notes to each business you add. This directory is great if you need to keep a record of different businesses that you will contact in the future.

Three Benefits of the MailWizz PHP Script

If you are running a business, then you will almost certainly be using an email service provider to stay in contact with your customers. 

There are many high-quality email service providers on the market today that can fit your specific needs, but they come at a high price. MailWizz offers you an affordable way to send out emails to your customers and enables you to only pay for emails that you send. 

Here are three reasons why MailWizz can be a great fit for your business.

1. You Only Pay for the Emails You Send

Email service providers such as MailChimp, Convertkit, and Constant Contact have robust platforms that can fit your email marketing needs regardless of your business size. However, these platforms can be very expensive. 

These platforms have a user interface for you to interact with and allow you to send as many emails as you need from their servers for a monthly fee. MailWizz helps you break free from this monthly subscription.

 By hosting the MailWizz software on your own server, you can hook up the email provider (Amazon SES, SendGrid, MailGun, etc.) of your choice to the MailWizz application and handle your email marketing needs this way. All you need to pay for is the low one time cost of the script and for the emails that you send. This will work out to being much lower than the cost of a subscription for the monthly payments.

2. It Comes With a Complete Set of Email Marketing Tools. 

Since there is only a low one-time payment, for the MailWizz application, you may think that it does not have as many features as some of the more expensive email service providers. This couldn't be further from the truth. 

MailWizz is a complete email marketing tool that has all the basic features as well as advanced ones. You can create specific campaigns, autoresponders, and send out mass emails with MailWizz just like with all of the other providers out there. A few advanced features that are included that other providers do not have are the control over your bounce servers, delivery servers, and feedback loop servers.

3. You Can Be an Email Service Provider for Someone Else

MailWizz allows you to start your own email SAAS business. Since the application is self-hosted, you have full control over the emails sent and who sends them. You can charge people to send emails through the MailWizz application and present them with payment gateways that give them access to specific functions and limits within the application. The users can have their own separate account on MailWizz that is separate from yours, so you can also use MailWizz for your own email marketing needs as well. Payment gateways, pricing plans, taxes, and promo codes can all be handled by MailWizz, so no further development will be needed to start your SAAS business. 

Here is the user dashboard of MailWizz that your potential customers will have access to.  Add a Premium PHP Scripts to Your Website Now!

PHP scripts can add plenty of features and functionality to your website for a low cost and almost no time commitment.

If you are running a business that needs to have all the features of a modern website then add one of the many useful PHP scripts available on CodeCanyon

The PHP scripts available will allow you to seamlessly integrate a useful set of tools into your website that your business will need to gain an edge over your competition.

There are over 4,000 high-quality PHP scripts on CodeCanyon that can help improve your business's website. Have a look through this massive collection of scripts and you'll find all sorts of scripts ranging from project management, social media, shopping carts, and much more. 

Find the perfect PHP script to help your business succeed today! 

Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.


Categories: Web Design

12 Best PHP Event Calendar and Booking Scripts... and 3 Free Options

Tuts+ Code - Web Development - Mon, 05/25/2020 - 07:24

In this article, I'll review 15 of the best PHP calendar scripts. Whether you need an appointment booking script, an event calendar script, or a PHP calendar reservation system, you'll find something on this list.

There are lots of reasons you might need a PHP calendar script. If you’re a service provider, you need an appointment booking system that allows customers to see your availability and select an appointment time and date that is best for them. This makes it easier for customers to book and cuts down on needless calls to your business.

Online calendars are also handy for organisations of any size to help team members share events and tasks and keep track of what everybody is working on.

Their usefulness isn’t just limited to companies, however. Artists, writers, performers, bloggers and anyone else with an active public life could make good use of PHP calendar scripts to let followers and fans know the whens and wheres of public appearances.

What Type of PHP Calendar Script Do You Need?

When it comes to PHP event calendar and appointment booking scripts, choosing the right one can be hard. They can take dozens of forms, and finding the right one for you can be a daunting task.

To help narrow the solutions down a bit, here are a few questions to ask yourself before you get started:

  • Do I need to focus on events, which occur at specific times, with a large number of tickets to sell? Or on bookings, with a smaller number of services that could occur at any time?
  • Will I need to support only my business? Or are there others that will be included in my listings? For example, a business cooperative might need to handle bookings for multiple service providers.
  • Will there be a single entity that events or bookings are attributed to, or several—as in a hair studio, with several stylists available?
  • Do I need a script to embed into a current site, or do I need something that stands on its own?
PHP Event Calendar and Booking Scripts on CodeCanyon

There are currently almost 50 PHP event calendar and booking scripts available on CodeCanyon. Some of these scripts address very specific use cases like cleaning and laundry services. Others are more general-purpose scripts used to book all kinds of events.

All of these scripts offer the basic functionality you expect in a booking system. Some of them also have a unique set of features that includes things like generating invoice PDFs or sending booking alerts through SMS.

After you purchase any of these scripts, you will get six months of free support to help you set things up. You also become eligible for free lifetime updates.

The Best PHP Event Calendar and Booking Scripts on CodeCanyon for 2020

With all this in mind, we’ve compiled ten of our best PHP calendar, booking and event scripts available for download today at CodeCanyon. This post will help you choose the one that’s right for you.

1. Cleanto

Cleanto is ideal for many different types of service companies looking for a reliable way to provide clients with full-featured online booking.

Standout features:

  • PayPal, Authorize.Net, and Stripe payment methods
  • email reminders
  • auto-confirm bookings
  • ability to add breaks in schedule
  • and more

User Crossera says:

“Amazing customer support. These guys came back to me within a day with a fix for all the problems I faced. The plugin can be customized to whatever your needs are.”2. Appointo—Booking Management System

An end-to-end solution for booking, Appointo Booking Management System takes the heavy lifting off your CMS or static site. This script provides a front-end calendar and booking system that can be easily used to mark appointments or events. Then, on the administrative side, you can manage the events and services that are available, and keep track of customers or attendees.

Standout features:

  • front-end booking calendar
  • ability to manage services and booking
  • point-of-sale support
  • customer management
  • support for both PayPal and Stripe
Appointo's admin dashboard in action

User moffei says:

“Cool and Clean Customer Support. The fastest customer support I've ever had on CodeCanyon, plus a better script for the job. I definitely recommend it.”3. Vacation Rentals Booking Calendar

The Vacation Rentals Booking Calendar is an online vacation rental booking calendar script that allows property owners or management agencies to create and manage rental availability calendars for their vacation rental properties.

Standout features:

  • highly customizable
  • email notifications to site owner or administrator
  • XML and JSON availability feeds
  • export calendars to iCalendar format
  • and more

User Craignic says:

“Great product and quick support given when I had a query.”4. NodAPS Online Booking System

The NodAPS Online Booking System promises to help you manage your appointments more easily. You can create unlimited accounts with administrative, assistant, and staff permission, and add unlimited languages to the system. You can also change the booking time and date with a drag-and-drop feature.

Standout features:

  • multi-provider system
  • seven different booking type forms
  • multilingual
  • easy to install
  • and more

User Jam79 says:

“Very simple to use. Fast and effective support!”5. Laravel Booking System

The Laravel Booking System with live chat offers a great online system for booking and making appointments. Users can buy credits as a payment option and view available services, total transactions, their total credits, and administrator contact information via their dashboard.  

From the administrative side, the system administrator can manage all things system related: general settings, payment settings, and user management. Admins can also manage bookings and respond to inquiries from their dashboard.  

Standout features include:

  • live chat
  • multi-language support
  • booking and transaction history
  • PayPal integration
  • and more

User brentxscholl says:

“This plugin works great. Great code. Customer service is fantastic. We asked for extended features and they were delivered for a reasonable price.”6. Ajax Full Featured Calendar 2

Ajax Full Featured Calendar 2 is a highly customizable personal calendar designed to help you keep organized. This is a best-selling update of another popular script, the Ajax Full Featured Calendar.

Standout features include:

  • PHP and JS versions with PHP classes and object-oriented programming
  • ability to auto-embed YouTube, Vimeo, Dailymotion, or SoundCloud media
  • ability to export calendar or events to iCal format
  • supports recurring events
  • and more

User sv_fr says:

“Great script. Practical uses. Helpful support.”7. Event Calendar

Built with jQuery FullCalendar and integrated into Bootstrap’s grid layout, the Event Calendar plugin allows users to organise and plan their events.

Standout features:

  • create new types of events
  • ability to add fields such as title, colour, description, link, and photo
  • Google Fonts and Font Awesome icons
  • and more

User teddyedward says:

“Really enjoy using your script—it's perfect for my needs. It's also well documented and easy to use.”8. eCalendar

Quite simply, the eCalendar script is designed to keep individual users or companies organised with a calendar that allows users to add as many events as needed, as well as updating details like the event title, location, or time.

Standout features:

  • choice of two designs
  • cross-browser compatibility (IE8+, Safari, Opera, Chrome, Firefox)
  • events are saved in your MySQL database
  • fully responsive design
  • and more

User levitschi says:

“Everything works perfectly! Support was better than I ever expected!”9. BookMySlot

Focusing largely on event bookings, BookMySlot takes it up a notch by allowing your site to handle multiple vendors, with their individual events nested underneath. This script is thorough and self-contained, so if you are looking for a turnkey solution, rather than something to add to an existing website, this could be the script for you.

Standout features:

  • thorough documentation
  • separate dashboards for admins and vendors
  • supports Stripe payments
  • built-in messaging system

User aungoo says:

“Outstanding customer support. I'm also happy with the quality of coding. ”
10. Laundry Booking and Management

This Laundry booking and management script serves a very specific purpose. This is good news for anyone who wants to create their own laundry and dry cleaning business. It has some great features, both for users of the service and for the business owner.

Users can book orders for services like washing, dry cleaning, ironing, etc. The user interface allows them to pick the number of different types of clothes like trousers, shirts, etc.

The business owner can get paid through a lot of payment gateways like PayPal, Stripe, and Authorize.net, among others. They will also get booking alerts via SMS.

Here are some other additional features of the script:

  • multiple SMS and email templates for users
  • guest checkout for orders
  • generate invoices in PDF format
  • staff dashboard to easily manage everything from one place

This fantastic script offers a lot of other features that you will find useful. If you are serious about starting a laundry business, you should definitely consider giving it a try.

11. BookingWizz Booking System

The BookingWizz System script has been around for over ten years now. It was added to CodeCanyon in February 2010 is still updated regularly today. And it has been receiving good reviews from its buyers all this time! So you can rest assured that it is a great booking plugin that will serve your needs well.

BookingWizz offers features like discount coupons with unique codes and expiration dates. All your sales stats are available for you to see in the dashboard. The design is also fully responsive and looks great on all kinds of devices and browsers as old as IE9.

Here are some of its other features:

  • unlimited calendars and events
  • hourly and daily bookings
  • integrated PayPal payments and offline payments
  • multilingual support
  • automatic booking reminder
  • printable PDF schedule
  • and more

You should try out some of its features in the live preview of the script and see if it does what you want.

12. Rezervy—Online Appointment Scheduling

Rezervy is a great online appointment scheduling and reservation booking script. It was added only recently to CodeCanyon, but the numerous five-star ratings of the script are proof of its quality.

Rezervy comes with both single-step and multi-step booking form features. The script creates a fully responsive booking system, so it looks great on large screens as well as smaller mobile devices.

There are many amazing features in this script, like:

  • support tickets
  • guest checkout
  • coupon discounts and recurring discounts
  • support for multiple currencies
  • manual booking
  • referral codes
  • rating and review for each appointment
  • and a lot more

Just try the live preview of the script, and you will be amazed by its design and functionality.

Free PHP Event Calendar and Booking Scripts

Creating a great PHP calendar script is hard. As a result, it can be hard to find quality scripts—especially for free!

That's why our recommendation is to try one of the CodeCanyon scripts mentioned in the article. They all offer a lot of features, and you will get six months of support and free lifetime updates.

Most of the free PHP calendar and event booking scripts either have a very limited feature set or have not been updated in a long time. There are some good options out there, though. Here are three of the best:

1. phpmyreservation

This is a very basic reservation plugin that you can use to take bookings for a single item like appointments with a dentist or a conference room. You can control the pricing of each reservation.

2. laravel-booking

This is a simple room-booking system based on Laravel 5.6. Laravel is a free, open-source PHP framework for creating web applications. So you need to be familiar with both PHP and Laravel to set it up.

3. laravel-google-calendar

This is yet another free PHP script based on Laravel. It allows you to easily create, delete or update any events in Google Calendar.

Tips for Using Event Calendars and Booking Scripts

Here are a few tips that you should remember when starting a business that's based on booking products and services.

1. Make Sure That the Booking System Is Responsive

People almost always have their smartphones with them. They usually also prefer to do things like booking reservations on their smartphones. If your booking system has a responsive layout that provides an amazing user experience, you will have a big advantage over your competition.

2. Don't Cram Too Much Information on the Screen at Once

Depending on the type of business that you operate, it might not always be possible to just ask users a couple of questions and book their slots. In such cases, use simple layouts that guide people throughout the booking process without overwhelming them. One great example would be the booking system by Rezervy.

Other PHP Scripts on CodeCanyon

These PHP event calendar and booking scripts just scratch the surface of what's available at CodeCanyon. There are over 4,000 PHP scripts available in the marketplace, covering everything from calendars and forms to social networking and shopping carts.

Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.


Categories: Web Design

7 Examples of Scroll-Triggered Animations in Web Design

These days it is quite difficult to imagine a modern website without any dynamic elements. Small, big, medium-sized they — will be there on many websites. Web user interfaces...

The post 7 Examples of Scroll-Triggered Animations in Web Design appeared first on Onextrapixel.

Categories: Web Design

Can Data Visualization Improve The Mobile Web Experience?

Smashing Magazine - Tue, 05/19/2020 - 04:30
Can Data Visualization Improve The Mobile Web Experience? Can Data Visualization Improve The Mobile Web Experience? Suzanne Scacca 2020-05-19T11:30:00+00:00 2020-05-20T10:51:42+00:00

It can be tough to prioritize the mobile experience when it often feels like a compromise. Don’t include as much text. Remove some of your images. Stay away from features that get in the mobile visitor’s way. It’s kind of like a parent who tells you, “Go out and have a good time, but don’t do X, Y or Z!”

It’s not necessarily that a mobile visitor needs a shorter page, less text or fewer images to more easily consume content on a smartphone. They just need the content you give them to not feel like so much work.

If you look more closely at your pages, you may find that some of the written content can be converted into data visualizations. So, today we’re going to look at some things you can do to start converting more of your content into graphics and enhance mobile visitors’ experiences in the process.

Quantitative Data Tools

Many UX designers are somewhat afraid of data, believing it requires deep knowledge of statistics and math. Although that may be true for advanced data science, it is not true for the basic research data analysis required by most UX designers. Read more →

1. Go Beyond Traditional Data Visualization Formats

When you think about displaying data in a graphical format, what do you envision? Probably graphs and charts like this:

A snapshot of an infographic from Visual.ly that displays web designer vs. web developer job statistics. (Image source: Visual.ly) (Large preview)

This screenshot comes from a Visual.ly infographic comparing web designers and developers. This particular piece of it deals with jobs-related statistical data, so it makes sense that it would be translated into bar graph and line chart formats.

As a writer, I’m a huge fan of this kind of data visualization because having to write out stats can be a major bummer. Like I know there’s a significant difference between the data points, but I can only use bold fonts and bulletpoints so many times before readers start to look for the next new interesting thing to focus on.

When strong data sets are designed rather than written, readers are less likely to skip over and unintentionally miss critical information. But it’s not just data that can be visualized. Take this other segment from the infographic, for example:

A snapshot of an infographic from Visual.ly that displays web designer vs. web developer right vs. left brain thinking. (Image source: Visual.ly) (Large preview)

This could’ve been written as a paragraph (e.g. “_In general, web designers are right brain thinkers, leveraging intuition, creativity, blah blah blah…_”). It could’ve also been displayed as a table:

Web Designer Web Developer Brain Hemisphere Right Left Driven By Intuition Logic Approach Creativity Linear Thinking Strength Imagination Technical

While this would’ve perhaps been easier to read than a wall of text, it’s not nearly as interesting as the graphic above.

In order to identify different kinds of data worth turning into graphics, it’s going to require web designers to do some thinking outside the box. I’d recommend you start by acquainting yourself with the different kinds of data visualizations that exist. You can use The Duke University Library for that. It has an entire page that shows how different kinds of information can be translated into graphics, like this example of a scatter plot:

The Duke University Library provides an example of a scatter plot visualization. (Image source: Duke University Library) (Large preview)

The Pudding took this basic concept of charting data points over time and turned it into something unique in its “Colorism in High Fashion” article.

This is a graphic that represents the spectrum of skin tones that have been represented on the cover of Vogue:

The Pudding depicts trends in the skin tones of Vogue cover models in its article “Colorism in High Fashion”. (Image source: The Pudding) (Large preview)

This is a much more effective and eye-catching way to relay this information than to have a writer say, “Over the magazine’s 200-plus issues, 75% of Vogue’s cover models tend more towards fairer skin tones.”

That said, this graphic on its own isn’t a scatter plot as it only depicts quantity and trends. However, scrolling does eventually turn it into a scatter plot:

The Pudding uses a scatter plot to display how Vogue cover model skin tones have changed over time. (Image source: The Pudding) (Large preview)

Notice how each of the orbs has been pulled out onto a timeline, representing the faces of the models on the magazine covers. This is not the traditional way to use a scatter plot chart, but, in this case, it works really well. And, again, it does a much more effective job in getting the point across on mobile than a wall of text.

As you look for ways to do this in your own work, hone in on the following elements:

  • Statistical data,
  • Short bulleted lists,
  • Highly complex topics,
  • Step-by-step explainers,
  • Page or topic summaries.

These present the best opportunities for turning essential data or topics into visualizations.

2. Design Your Data Visualizations To Be Filterable

Of course, you don’t want to overdo it. In your mission to preserve your website’s message on mobile, you don’t want to create so many graphics that it compromises page speed or that they start to feel overwhelming.

One solution to data visualization overload is to create a single graphic, but use filters to control which data sets are displayed. Not only does this enable you to deliver a ton of visual information in a smaller amount of space, but it can become a competitive edge, too. Let me show you an example.

The reason why a CDN is useful is because it puts your website geographically closer to your target audience. If the CDN doesn’t have the reach to do that, then it’s not worth the trouble. That’s why, of all the considerations people have to make when finding a provider, they have to look at where their points of presences actually are.

This is how Google Cloud displays this information for its content delivery network:

Google Cloud uses a static map to display its CDN PoP locations to prospective users. (Image source: Google Cloud) (Large preview)

This is a great graphic as it shows where its cache locations are and how broad of an area the network covers. However, this is a static image, so what you see is what you get. Google has to use the rest of the page to list off all the major cities where it has a CDN presence:

Google Cloud publishes a list of all its CDN cache locations around the world. (Image source: Google Cloud) (Large preview)

But this is what I’m talking about. This list should be part of the visualization.

Akamai, a competitor to Google Cloud CDN, has designed its media network map this way:

Akamai’s media delivery network map shows all its media and storage point of presences. (Image source: Akamai) (Large preview)

On this map, you can see Akamai’s media delivery network (in orange) and its media and storage locations (in pink).

Prospective users interested in going deeper into the data can use the filters at the top of the page. For instance, this is what the map looks like when someone searches the Asia region:

Akamai’s media delivery network map with a focus on the Asia region. (Image source: Akamai) (Large preview)

And this is what they see when they choose to view Akamai’s storage network against its competitors:

Akamai’s media delivery network map set to view Akamai’s Asian storage network against its competitors. (Image source: Akamai) (Large preview)

Not only does this data visualization design let visitors closely survey the data that’s most relevant to them, but it aids in their decision-making process, too.

This approach is really useful if you want to turn a whole bunch of data into a data visualization without having to overwhelm the page with it. And with this particular model of filtering, you can spare your visitors the trouble of having to pinch to zoom in and out of the graphic. They can customize the view on their own and get to the most relevant bits with ease.

3. Make Your Data Visualizations Interactive

Another thing you can do to pack a ton of information into a single graphic is to make your data visualizations interactive. Not only will this declutter your mobile UI, but it’ll get your visitors to pause and really take time to understand the information they’re being shown.

This is a recent post from Emojipedia. The article shares the results of a study they conducted on emoji usage during the coronavirus. It’s a fantastic read and it’s chock-full of data visualizations like this one:

An Emojipedia article on coronavirus emoji usage includes data visualizations throughout. (Image source: Emojipedia) (Large preview)

The design is certainly attractive, but it’s not easy to see all the details within the graphic on mobile. This is where interactivity would come in handy.

By making each of the bars in the graph clickable, people could get more information about the emoji, see the percentage increases clearly, and so on.

Something I didn’t show you in the last point is that the Akamai CDN map is interactive:

Akamai’s media delivery network map is interactive. (Image source: Akamai) (Large preview)

This is the exact approach I would suggest for the Emojipedia bar graph. By turning each data point into a clickable element, users don’t have to struggle to gain all the information they need nor do you have to overwhelm them with too much data within a single graphic.

What’s nice about interactivity is that you can apply it to a wide array of data visualizations, too.

Here’s an example of a bubble chart from Information Is Beautiful:

A graphic from Information Is Beautiful that depicts the most serious data breaches around the world in bubble chart format. (Image source: Information Is Beautiful) (Large preview)

When visitors click on any of the bubbles, more information is revealed about the security breach:

A graphic from Information Is Beautiful with information on a major Zoom security breach and data loss. (Image source: Information Is Beautiful) (Large preview)

One of the great things about prioritizing the mobile experience is that it allows us to find creative solutions to designing minimally. And interactions are a really good way to pull that off as the UI remains clear and easy to navigate, but tucked within it are juicy little nuggets waiting to be discovered.

Is Data Visualization The Key To A Better Mobile Experience?

There are a lot of things we can do to improve the mobile user’s experience. If you haven’t considered data visualization part of that strategy, now would be a good time to as it enables you to:

  • Condense the amount of space and time it takes to get your point across,
  • Design your pages to be more visually engaging,
  • Preserve the full integrity of your copy for mobile and desktop visitors.

That, of course, doesn’t mean that you should stop looking for ways to reduce content on mobile. If it’s unnecessary or doesn’t add value, it should go. What remains can then be evaluated for a data visualization makeover.

(ra, il)
Categories: Web Design

Smashing Podcast Episode 16 With Ben Frain: How Can I Optimize My Home Workspace?

Smashing Magazine - Mon, 05/18/2020 - 22:00
Smashing Podcast Episode 16 With Ben Frain: How Can I Optimize My Home Workspace? Smashing Podcast Episode 16 With Ben Frain: How Can I Optimize My Home Workspace? Drew McLellan 2020-05-19T05:00:00+00:00 2020-05-20T10:51:42+00:00

In this episode of the Smashing Podcast, we’re talking about shaping our physical spaces when working from home. What can you do to take a step up from working at your kitchen table? I spoke to workspace geek Ben Frain to find out.

Show Notes Weekly Update Transcript

Drew McLellan: He is a web developer, author, and public speaker who specializes in CSS architecture, methodology, and training. Hailing from the UK, he currently works as a UI UX design technical lead at Bet365, but you might know him better from his books such as Responsive Web Design With HTML5 and CSS, and Enduring CSS, both from Packt publishing. He also writes for Smashing Magazine, and you may remember his series last year on building progressive web apps without a framework. We know he knows his way around the bottom web development landscape, but did you know he owns more trousers than socks? My Smashing friends, please welcome, Ben Frane. Hi Ben, how are you?

Ben Frain: I’m smashing, Drew.

Drew: I wanted to talk to you today about something slightly different from your usual specialism of CSS architecture. With social distancing measures in effect, many of us are finding ourselves needing to spend some serious time working from home. And in a quest to be productive, we might quickly find that our home workspaces aren’t necessarily the best equipped or configured to help us to work well and remain healthy. So, I wanted to talk to you a little bit about workspaces, and generally the things people might want to think about when they find themselves working from home. This is something of an interest of yours, isn’t it?

Ben: It is a little bit. I’m what you might describe as a mechanical keyboard aficionado, but I’m also tend to get myself quite obsessed about getting a physical workspace right. Obviously, a great, many of us, myself included, have been dumped in our home offices or whatever we deem to be our home offices for the foreseeable. And so, you’re continually making that trade off of trying to decide what do I invest in to make myself comfortable and get work done without wanting to spend thousands and thousands of pounds, dollars on stuff that potentially you’re not going to use for a long time. So, I think everybody or a lot of people are making these decisions about what stuff they can grab from somewhere else and what things it’s worth investing in to make things more comfortable. The old adage is always spend your money on your chair and not your desk, and I think things like that are good advice.

Drew: I mean, transitioning to working from home, I think many of us find ourselves working from a sofa or hunched over a laptop at the kitchen table. That’s not really the best way to work, is it?

Ben: No, it isn’t. I mean, I can remember the old house where I used to live, because I had a day job, like a lot of other people and then I’m writing books in the evening, and I can remember spending months at a time where I would put a bread board on my desk hub and my laptop on top of that, and that was my standing desk in the evenings, which actually wasn’t so bad because it did force me to be up right for decent portions of the day. I was looking at before the whole COVID thing came about, because I’d started to write another book in the evenings. I’d made the deal with myself that I would buy one of these electronically adjustable standing desks which I found great utility in. It was a lot of money at the time for a desk because … I mean, obviously, people decide what they want to spend the money on differently, but it always felt like a bit of an indulgence.

Ben: But having had it now, I think it’s worth every penny and I really enjoy the fact that I can sit for a bit and then stand for a bit, and there’s not … You can get the manual ones where you crank a handle like an old 1920s car to get the desk up and down. I went for the electronic one even though it’s quite a bit extra, but I’m glad I did because I’m lazy and I probably would never use that handle.

Drew: So, if we’re looking to move off our kitchen table and think about getting some sort of desk, sit stand is one thing to bear in mind, are there other considerations we should make with a desk?

Ben: Yeah, I mean, I think the actual sort of the desk top itself, you can get very inexpensively, even places like Ikea, which have obviously been thrashed with everybody trying to get hold of an inexpensive desk at the moment, but you can still get a slab of wood fairly inexpensively. I mean, chair is obviously the big one. I mean, I’m lucky in that touch wood, I’ve never had any problems with back or any of that thing that is typical of people that work at computers all day. But I think even things like a popular one that you see is like the Herman Miller Aeron, is one of the very popular maker chair, but really quite expensive. But you can pick them up around $300, something like that refurbished, which is probably when you’re trying to decide where to put your money to be comfortable for a whole day’s work, it perhaps isn’t as bad as it sounds. And then obviously the same, I know some people struggle with RSI, so I know a lot of colleagues of mine have got the vertical mice which is they’re relatively popular to prevent that, which again, more expensive than your typical mouse, but people don’t always consider the fact that.

Ben: I know trades people who work as builders and that they will think nothing of spending a few thousand pounds on a particular piece of kit. And yet often we will just use whatever comes stocked with a computer that we have and we’ll bulk at the idea of spending a hundred dollars on a mouse or $200 on a keyboard. And yet really we have a relatively low entry point in terms of cost in order to do what we do. I think we have a tendency to be a little bit perhaps cheapskate in that regard. But if you find yourself getting physical problems or you’re not as comfortable as you may be, it perhaps is worth thinking about those things before buying other things I guess.

Drew: I guess preventative expenditure on decent chair for example, will save you an awful lot when it comes to medical bills and physiotherapy or anything like that that is required to put the problem right.

Ben: Yeah. And I suppose it’s all conducive to you being good at what you do or being the best that you can at what you do. If your limitation is a kit that you use, and you can alleviate that limit, then it seems sensible to do so.

Drew: So if we’re thinking about spending money on our work environment, if we’re currently sat at the kitchen table on a wooden chair or whatever, you’d reckon a chair is the best place to start?

Ben: That would be my advice. Yeah. I mean, I can’t profess to be an authority on these things, but it seems it’s a sensible, it’s probably the single most important thing you could do to make yourself comfortable throughout the day. You can start with something fairly expensive. I made the same mistake and I ended up getting a 45 pound office chair from Amazon and I didn’t realize that it didn’t have a tilt forward, whatever the right word for that thing is, on the axis. So what I found is it was digging into the underside of my thighs, behind my knees and I was thinking, why are my legs going dead after 45 minutes of sitting in that thing? And you just don’t, I think particularly if you work for a company that provides decent office chairs, you just take them for granted and it isn’t until you look at that particular make and brand that you go, “Oh my God, this is a $700 chair.” When you realize that crikey, people have thought about this and done a lot for you and then obviously you come to your home environment and you think, “Why not spending X hundred dollars on a chair?” But maybe it is worth it. Particularly if you’re here for the long haul.

Drew: And we talk a lot as developers, don’t we? About this productivity consideration of being in the zone and being able to get in the flow of writing code or working on a thing and time just seems to pass by and you can be super productive. Well, one thing I’ve found that can pull you out of that zone quite quickly is needing to stop and stretch because your legs have gone dead or your back’s aching. That can really disrupt your productivity as well as the longer health implications of that.

Ben: I mean, what have you found true in your situation? What have you done? What have you found the most effective?

Drew: So at the moment during lockdown I am staying with my parents, so I’m on my mother’s desk, which has a filing cabinet on one end and a bookcase on the other. So it’s all a bit makeshift. But at home normally, I do just have a couple of the cheapest Ikea desks organized in an L shape. So I tend to work with a couple of computers, and I have one on one and one on the other and spin between them. I used to have a lower back complaint quite regularly in my twenties where I would be sat on my desk for long periods and occasionally every few months I would find I couldn’t get out of bed in the morning because something in my back had gone. And the thing that immediately helped with that was, as you were saying, the tip forward seat angle on a chair. So having a chair that did that immediately helped because I think it resolved my posture.

Drew: So that helped immediately, but longterm what has helped and what means I don’t have any back problems at all now is just improving my personal level of fitness and activity. And that just having a bit more core strength and being just a bit more fitter and a bit more active has meant that I can actually, I can sit in some fairly bad chairs and things for a while and survive it. Yes, very much immediately having a chair that would tilt forward just to bring my back up and get me into a good posture, that was a definite, definite improvement for my back immediately.

Ben: Yeah. I mean, that’s interesting because it’s another thing that I guess a lot of us are missing now is, I mean, I’m by no means a gym rat at all. I just go because I don’t want to die essentially. But things like good barbells with plate weights, I naively thought, well, I’ll just go to my local shop. I’ll be able to get some of those maybe a hundred pounds and then you realize that a decent barbell itself is $200 at least. But obviously stuff like that and keeping yourself in a decent physical shape whilst you’re a couch potato is quite important as well. So much to think about for the people that have not been working from home and all these things become apparent very quickly.

Drew: Definitely. And in terms of working from home, one of the things I find that I’m doing a lot lately is spending time in virtual meetings via Zoom or Skype or whatever. Are there any things, any considerations you’ve made in terms of making the environment better for being on calls?

Ben: I suppose. I mean, obviously putting your screen away from all your socks and pants, that’s probably quite important. I mean, I’ve found as well that perhaps try and be conscious of the fact that at first I was raising the desk because I’ve got this desk that will raise up and a couple of people said to me, it looks like you’re about to tell me off because I was looming over them because the … long story short, I suppose making sure that when you take calls, it’s quite nice to be looking directly into the webcam. I always tend to ask people if possible, if we can do a face to face call because I think one of the things we’re incredibly lucky in this situation about is that speaking on a video call now is so much better or even when you didn’t even have it 20 years ago. And being able to see this nuance in people’s expressions is so much more useful on a remote call than just hearing the voice. And so if you’re going to do that obviously, being able to look straight down the camera or so that they can see you not at some weird awkward angle and there’s some okay lighting in the room, I say this as I look at myself half and dark in this situation, but those sorts of things are worth thinking about I think.

Drew: One thing I’ve found has really helped with my setup is I’ve got a big LED panel light. It’s called an Elgato key light, which is on a big stand.

Ben: Oh, like a big uplighter sort of thing?

Drew: It clamps onto the desk and is on a big pole and then sits above the monitor and shines a blanket of light down on there.

Ben: Oh, that’s pretty good. So it’s more like a daylight kind of light I take it?

Drew: Well, yes. You can actually adjust the color temperature and the brightness of it from software on your desktop.

Ben: How can you tell a difference if you use that light? Does it feel better?

Drew: It makes a big difference. Yes, especially you get often with webcams. You get the situation where the background is more lit by the windows in the room than you are and the camera doesn’t expose for the right thing. So making sure that you as the subject and nice and bright in the frame really helps the camera to get good focus and therefore your facial features are clearer and you can communicate well that way.

Ben: These are like Hollywood techniques, truths. Incredible. I mean, does that help as well with things like glare on your screen because you get in a more even diffused light in the room? Or have you not noticed?

Drew: It’s not particularly lighting the screen. No.

Ben: Okay.

Drew: I mean, glare on the screen is a definite thing that we should really think about in terms of workspaces. Where I am here, I’ve got conservatory windows at the end of the rooms. There’s a lot of light flooding in there.

Ben: I was just going to say, just what you need.

Drew: First thing in the morning, it can be very, very difficult. I have my editor set on a dark theme usually. My code editor. And so then I often find that I’m not using the left hand side of my screen, which is slightly washed out by the windows and I move everything over to the right side.

Ben: And do you think that’s a subconscious thing? Just because I just can’t see it so I’ll concentrate my efforts elsewhere.

Drew: But actually probably what I should be doing is switching to the opposite color scheme in my editor. I should be switching to dark text on a light background perhaps during the day.

Ben: They’re not cool anymore though Drew. Or didn’t you get that memo?

Drew: It’s not cool, no. But neither is failing eyesight.

Ben: No, no, definitely not.

Drew: One of the sorts of things in people’s workspaces that perhaps they don’t think of so readily when you think about optimizing how you work is perhaps one of the most common input devices, which is the keyboard. You wrote recently for Smashing Magazine on the subject of mechanical keyboards, which are seeing something of a Renaissance, aren’t they?

Ben: Yes, that’s right. It is funny because I always say to people, I get… because in my circles, people that I know, people are aware of my minor obsession with these things. And so I get asked quite a lot about them. And over the months and months of this, I thought, it’s one of these sorts of areas, which is because it is quite niche you tend to end up on a particular forum for this topic and you very quickly feel like, “Oh my God, this is a level of geekery beyond something that I’m comfortable with.” And that comes from somebody who’s relatively geeky. But I think there’s definite merit in them in terms of, I would never say to somebody, this is something you absolutely need to make you better at what you do. It more falls into the camp of, because you can get a mechanical keyboard, which makes you feel productive and in some weird pseudo way that makes you more productive. So many of us take the keyboard that comes with our system.

Ben: I never think about it any more than that. And just off we go. But I was surprised once I started looking at all the plethora of different layouts that you can get because I just wasn’t aware of the fact you can get these tiny little 40% size ones, you can get 65% ones which do have the arrow keys and some of the others, but lose the function keys. And it was only when I really started to analyze what I did with a keyboard and the keys that I pressed that I realized there was whole areas of keyboard, which is taking up often a substantial portion of your free desk space where you might prefer to jot stuff down and all the rest of it. And I realized that this big desk commander that I was using with a dedicated number pad was just an indulgence really. And I thought I needed those keys and it turns out I actually didn’t.

Ben: So, aside from the physical considerations, there’s just a very nice, I mean, mechanical keyboards often, you put one in front of somebody who’s not seen one before and they just laugh and think that it’s something out of war games from the 1980s. But once you overcome the fact that it isn’t a sleek, minimal thing like that and you actually use it and you get a feel for the key travel and stuff, you actually realize that there’s a rhythm that you can get with them, which you can’t get with these very shallow chiclet keys that we’re used to on keyboards nowadays and often things like iMac and the light ship with these very, very slim keyboards with very minimal travel on the keys, which are fine but this is obviously, we’re talking about keyboards that are the other end of the scale.

Ben: So I always say to people, let’s be clear, this isn’t an exercise in good economics because they’re very expensive when you can go and get a 15 pound keyboard from your Tesco’s, Walmart, et cetera. But it is an investment in your own sort of, I mean, the joke I allude to in the Smashing Magazine article is the Rifleman’s Creed, which is a soldiers tool as it’s rifle. And for us more than anything else, it’s the keyboard. And so it’s finding something that particularly suits your needs and you enjoy using and you take care of and get the most out of as you can.

Drew: As you say, I think of mechanical keyboards a bit like using the keyboards that were on computers when I was growing up in the 1980s, A really retro style of technology. Hasn’t technology moved on, on the keyboards, that ship with modern computers just better than that old technology?

Ben: Well, I think the funny thing is, better is a subjective term. And so typically we have become accustomed to these very, taking the ones that ship with an iMac for example, which are incredible pieces of design, very slim, very elegant looking, but in terms of actual feedback to the user, the key travel that you get, I’ve just found it’s incomparable “proper keyboard”. And so once you kind of, if you eliminate, if you can embrace that aesthetic of the retro keyboard if you like and get over that and actually just use one for a little bit, I don’t know many people, well, I don’t know anybody that’s gone down that path and then backed back out and gone, “Actually I prefer the really shallow travel, I like the really cramped arrow key set up.” Because for what we do, whilst it’s lovely on a laptop because it lets you have a lovely sleek laptop that you can take different places, if you’re sat in front of a machine and you’re using that, and code is more than anyone else because we tend to have less reliance on the mouse.

Ben: Those keys are doing stuff for you. They’re working for you. So I don’t think you want a tiny little arrow key cluster. I don’t think you want a page up and page down doubled up on another key. These are the sorts of things that once you try and analyze how you work with your keyboard, it opens your eyes a little bit. So it’s a bit of an undoing of the aesthetic norm and the, what society tells you your keyboard should look at and how it actually works for you. I don’t know if that makes much sense?

Drew: Is it just for programmers that the mechanical keyboards are useful or do they have wider appeal than that?

Ben: Oh, I mean, the writers are the big proponents of them I suppose. I know for example, I think there was an anecdote of Terry Pratchett. He famously, once he found the keyboard that he liked, he bought 10 of them just because he never wanted to not have that keyboard because it was like you’re saying it’s about you don’t want that friction. You don’t want something to throw you out of your zone. It’s basically anybody who types on a keyboard for a long period of time rather than just casual use I think. Whether you’d go the route, if you’re somebody that’s jotting about to lots of different locations, you can get fairly compact mechanical keyboards as well that have got Bluetooth. I mean what keyboard do you use at the minute Drew? What’s your sort of-

Drew: Up until very recently, I’ve been using the iMac flat.

Ben: Yeah, the chiclet key one.

Drew: But after reading your article on Smashing and chatting to some colleagues at Netlify, a lot of them are very big mechanical keyboard nerds.

Ben: Oh, Okay.

Drew: I’ve decided to dip my toe in and I’ve got a mechanical keyboard on my main development machine. I’ve been using it about four weeks, I think about four weeks. And I’m finding that I’m very slow and making a lot of typos because it is so different from the very flat. I mean, the keyboard that I’m used to is basically like what comes with a laptop, just so flat, very low travel. And I’ve been using a keyboard of that style for maybe 10 years since Apple first started doing those as external keyboards. So then moving to something with much further travel and finding a keyboard with an angle to the keys is quite strange. I’ve had to prop it up quite a lot at the back to bring the keys forward to me a bit because I was finding that the whole angle was very strange and that has helped. But I’m finding I’m very slow, but I am getting faster and I am making fewer mistakes. I’m getting used to it. But I’m actually enjoying a lot of utility. The particular keyboard I’ve got has got a screenshot button.

Ben: Never knew you needed.

Drew: No, I know. There’s a key combination to activate during the screen capture, but this keyboard has got a button that does it. Actually, it’s something I do multiple times a day. In pull requests we tend to include a screenshot. This is what it looked like before, this is what it looked like after.

Ben: Right. Okay.

Drew: So it’s something I’m doing all the time. So having a dedicated key for it I found is actually incredibly useful and I’m feeling the benefit of that.

Ben: I think one of the other things that’s really good in some of the modern mechanical keyboards as well is they often have, they’re entirely re mappable so that you can put macros onto keys and you can, like for example, I have the shift key on mine set so that if I just tap it, it gives me a right bracket or parentheses and U S terminology, which in itself is quite useful for functions and all the rest of it. But if you’re using them and you want to skip along in normal mode through sentences, it’s that key that you do, which would normally be a hold on the shift and press the bracket key. So again, it’s about trying to analyze what you’re pressing day to day and thinking around that.

Drew: Mechanical keyboards in my experience tend to be a bit noisier.

Ben: They can be.

Drew: Is that a consideration? And if you’re working in a shared workspace, are all mechanical keyboards loud by definition?

Ben: No, they’re certainly not. And I think like all of us, when you first think of mechanical keyboards, if you have any idea of what they are, you think of these giant clicky clucky. When you’ve got the keyboard warrior that you’re speaking to on a screen share and you can barely hear the voice because all you can hear is this machine gun of keys. However, the main switch types or the clicky ones, which are the ones that we’re talking about there.

Ben: There’s then tactile switches, which give you the same travel, but you don’t get the physical and audible click as you push a key down. But then there’s also linear keys, which are just straight up and down, but you can also get silent variants of nearly all of them. If you are somebody who needs to sit in an office next to somebody, they’re probably the sort of one that you should go for. And then they’re no less, they’re physically just as nice to use I would say. I know that some people say they actually, the rhythm of the sound helps them to feel productive. Which I do understand that, but obviously if you’re working amongst other people, your productive might be somebody else’s disruptive.

Drew: What are the things that somebody should look for in terms of mechanical keyboard? I mean, it all starts with the keys, the bits you actually touch. And they can vary quite a lot.

Ben: Absolutely. So there’s the aesthetic side of it, which typically we developers and designers, we have opinions about what we like and every conceivable color and the way even that the legends are printed on the keys. You get some hot shots that just do away with the legends altogether and they just like some blind magician know which buttons to press. I’m not one of those. You also get people that can put the legends on the front side of the keys. And there’s also little things that for the longest time, looking at this keyboard, I’ve got on the J key and the F key, a little hump, which I assumed that was something to do with the manufacturing process.

Ben: But it turns out they’re homing keys so that you can rest your fingers on them and feel where you are on the keyboard. And then there’s also different sorts of plastic. There’s different angles to the keys themselves. I suppose if I was speaking to somebody who’d never had of mechanical keyboard before, although it sounds like a copout, I would probably just say, pick one you like the look of to begin with because the chances are you don’t really know what you like until you try it and try a few and sadly that’s where the cost of this obsession comes into play because you might find yourself going through three or four keyboards until you find one that you feel really suits not just the key switch type but the key cut material, the layout size, how customizable it is or isn’t. And a bit like the code editors, you have to be conscious of the fact that I could quite easily spend two days just messing around, setting my code editor up. Whereas really I should myself a big slap around the face and after a very limited amount of time, just get on with using it.

Ben: So it’s like all of these things you do have to be conscious of the fact that you can indulge yourself too much into these things. So I would say get one, use it. The primary concern that, as you alluded to before, should probably be whether you want a silent one or a clicky one to begin with because that’s the thing you can’t easily undo. A lot of them these days also have what’s called hot swap sockets, so that if you get yourself a keyboard and decide you actually hate the feel of these switches, you can pull them all out and put a different set of switches in, which is not necessarily cheap, but it’s a lot cheaper than getting a whole new keyboard. But the resale value in these things is typically very good anyway. So if you spend a couple hundred dollars on a keyboard, you probably get 150 back, even like six, eight months down the line if you needed to.

Drew: As you mentioned, there are all sorts of different types of switches that can exist under these keys. They’re called key caps, aren’t they on the top? Which is the bit that you actually touch. But then underneath those you’ve got different switches.

Ben: Yes.

Drew: I found personally that I had no way of being able to comprehend what switches I might want without being able to try them out. And of course at the moment in particular, it’s very difficult to try out anything. You can’t go into a store. I mean, even if you could find one. Is there any default switch you’d recommend for somebody if they didn’t know where to start?

Ben: Yeah, I think I would say that if the idea of a clicky one appeals, what you should be looking for, it is a slightly confusing thing. There’s basically colors which … so Cherry MX who were the original makers of the majority of keyboard switches that you get in mechanical keyboards, they designated MX Blue as the clicky switches. And what you get now is even though other companies are now making what’s called MX compatible switches, which is a different company creating the same style of switches, they follow on that coloring convention. So typically blue switches, whether it’s Kaihl or Cherry or somebody else, or your clicky sort, a brown will be tactile, what’s called a tactile switch, which is you get that same resistance at the top of the key press, but without the click sound.

Ben: If you like the idea of a key which doesn’t have any resistance and it just travels up and down in a linear fashion, a linear switch, you’d be looking for something which is called an MX Red or equivalent. And then something which is more silent, they’re typically designated as quiet switches or silent switches. There’s a whole different camp of keyboard switches by a company called Topre, which is based in Japan. But that’s probably something I would say not to worry about for now because they tend to be both more expensive, harder to come by and I would probably try and rule out by saying go for one of the easier to come by MX variants first.

Drew: I chose MX Brown for my first keyboard.

Ben: Yes, I think I did the same as well.

Drew: I’ve no idea whether I like them or not because the whole thing is so new. The one thing we need to keep in mind I guess is different layouts of keyboards. I mean, I work with MX and obviously lots of people got PCs and various other things. Is that something to bear in mind when choosing a keyboard?

Ben: It’s almost a non problem these days. It used to be that some of the manufacturers, Filco for example, which they’re a good manufacturer of mechanical keyboards, but they used to have problems with Mac compatibility. Which you could work around with software for the Mac. It was a tool that used to be called Key Remap or something like that. It’s now called Karabiner, it’s a freeware piece of software which gets around the problem, but it was just an extra little bit of faff that you had to do. But typically nowadays with either dip switches on the bat, which are little tiny physical switches or the keyboard will have their own way of pressing certain key combos to program where the super key is so if you’re on Lenox it’s super key or we have the Mac key or the Windows key and you can typically swap all those sorts of things around with no problem at all. So it’s really more a case of … I mean, the example I gave in the article was there was a freeway piece of software which lets you, you stick it on to record and it logs your key process, which obviously you need to be sure that you’re comfortable with that to begin with.

Ben: But you can leave that thing running and it will produce a heat map of which keys you press and how often you’ve pressed them and all the rest of it. And often you’ll find that your expectation doesn’t match with the actual data. And that can therefore influence whether you want a keyboard that’s got a big number pad. If you’re somebody that works with Excel all the time, you more than likely going to make use of that. But if not, you might find that actually you just don’t need that whole section of the keyboard and you can go for something more compact. Also, the other thing going back to comfort is ergonomic keyboards, which most of us at some point have seen somebody with one other Microsoft natural keyboards where you’ve got the slightly turned sets of keys for left and right hand.

Ben: In the mechanical world there’s a few different ergonomic keyboards. The big one being the Ergodox EZ which again we mentioned in the article, but that’s not only two separate keyboard panels, but it also lets you adjust the rake of the key panel as well. So you can very easily change exactly the shape of those key pads and where they are. So again, although they’re not cheap, if you’re somebody that suffers with RSI and the light doing a lot of keyboard work, it’s perhaps worth looking at one of those.

Drew: Now, when I was looking at mechanical keyboards, I discovered that there were lots and lots of options I could build that came pre-assembled, ready to go, just plug in an and off we go. But there were also lots that seemed to come essentially as kits or as just a board and you could buy just switches and you could buy just key caps and you assemble it all yourself. That sounds pretty daunting.

Ben: Yeah, I mean it is and I would certainly say if it’s your first mechanical keyboard, don’t go there. It’s too much to take on at once. If you do find yourself enjoying keyboards as it were, it’s a bit like a Lego or a Meccano set. I recently did the first keyboard build of my own, having had them for four or five years. And that involves soldiering the switches onto the board and all sorts, which is not a level of geekery that I would suggest for the casual use. Just get a keyboard and make use of it and see how you like it first. But because they are getting more and more popular, gaming in particular is where they’re really starting to find a market now because you’ve got gamers who are obsessed with the shortest possible input lag of them pressing the space bar or whatever they’re pressing to nuke somebody or whatever it is that kids these days do. I’m out of that loop now. But that’s where they’re gaining notoriety and popularity and you’re getting the big peripheral brands like Logitech getting involved and Corsair that now make mechanical keyboards. So you’re getting more and more of this stuff is more easily accessible and easy to get a hold of.

Drew: Moving on from keyboards slightly or I mean perhaps, maybe not. Earlier in the year, you had an accident didn’t you? And lost most your finger, is that right?

Ben: Yeah. So I’ll give you the short, your notes version of it because it’s quite a story. I was essentially, it was early February and it was one of the first days in the UK, we had snow that year. And as is typical in the UK, if a snowflake falls, the entire infrastructure grinds to a halt. And so we were stuck in traffic having come back from the gym at lunch, it was five of us in the car. And we said, well, we’ve got a meeting at three o’clock and it was like five to three, we weren’t far from the office. Let’s just take a shortcut through this bit of land, which we’ve done many times before and we’ll get back to the office. And as we went through the other lads went one way. Three of them went one way and I carried on the way that I already knew and got to a bit and a new fence had been installed, but it wasn’t a sketchy walking fence, it was an every day, brand new, no sharp, edgy bits, nothing like that. Lots of footholds. It was maybe six foot tall, this sort of fence is an average person.

Ben: You’ve probably been over a hundred times before and would’ve thought nothing of it. So I climbed at one side, hung on the other and then I was maybe three or four inches from the floor and dropped off. I felt a bit of a weird twang in my hand, so I wondered, “Oh, I caught my wedding ring there on the fence, I wonder if I put a mark on it?” Glanced down and there was very little of my finger left. So it turned out that on the side of the fence I couldn’t see there was, where the crosses terminate, I had caught my wedding ring on it and it essentially yeah, removed the biggest part on my finger. And so very, very bizarre set of circumstances as it was then trying not bleed everywhere. At the same time find the other part of my finger and hopefully could stick it back on. In my naivety, I thought, “Well, as long as I can find the finger, this is easy these days, they’ll just few stitches, I’ll be back in the game.” But it turns out when you do it’s called a ring avulsion. And I don’t know, it’s actually quite common.

Ben: They told me up at the hospital that I went to that they get at least one a weekend, which I was crikey, I really would’ve liked to receive that memo. I perhaps would have thought twice about wearing a wedding ring. But because it’s sort of, without being too grim about it because it’s torn away from your hand, the ligaments get pulled from down in the palm of your hand as well. So it’s almost impossible for them to put it back. So long story short, it’s by no means fixed now, but it’s on the way. It’s probably going to be 12 months until it feels, I wouldn’t say painful. It’s uncomfortable more than anything. And obviously getting used to the fact every day you wake up in the morning and like look and “Oh my God.” Mentally, it’s quite a hard adjustment to make. But very quickly I was able to use the keyboard. But it’s funny because your mind still thinks you’re at the end of your finger as where it used to be.

Ben: And so you’re missing a lot of keys as you type and you have to make that adjustment that Oh, actually that finger’s not there anymore. So these particular key combos that I’m used to doing and have been ingrained in my mind for years and years and years, you have to unpick and redo. But I guess the human mind has an incredible capacity to work around these problems. And I don’t feel now even just … so that was 10th of February. Here we are beginning of May, I don’t feel now like it’s a hindrance, particularly on the keyboard. Things like lifting waits or rowing or something like that, you can certainly still tell a difference. And I think it’ll take a while for my hand to get stronger again.

Drew: Were there any adaptations that you needed to make other than the mental adaptations when it comes to typing? Is there anything else about your workspace or anything that you’ve noticed you needed to change?

Ben: I don’t think there has been really, I mean, in an odd way I’ve been very lucky because that particular finger is probably the weakest finger that you have anyway. And it’s on for me, my nondominant hand. I didn’t realize at the time, but apparently your little finger is 40% of your lifting ability. It comes from your little finger. So they said, “If you’d had lost your little finger, it would have been far greater implications.” And obviously your thumb is a really big deal. So in a weird way they said, “If you were going to lose a finger, that’s the one to go for.” Great. But the funny thing is in terms of actually your typing speed or whatever, your brain almost didn’t have to consciously do anything at all. It just remapped over maybe three or four weeks. I was away from work for two weeks, but I still had a book to finish. And so I was using that as my practice. Trying to get back up to speed as soon as I could. But yeah, a very bizarre set of circumstances. You always arrogantly assume these kinds of things out into other people and then one day it happens to you.

Drew: Exactly. Yeah, I think so many people who note the fact that they are suddenly needing to benefit from what we consider to be accessibility features of the work that we do. It’s not because they’ve had an incredibly traumatic life changing incident or there’s not that they were born in a particular way, but just something smaller, a minor break of an arm or a losing a finger or any of these things. Failing eyesight can just bring home the need that actually, accessibility is something that we all rely on even just as we age.

Ben: Yeah, absolutely. I mean, it’s funny because I’ve always been mindful of accessibility for sure. But I don’t think I was perhaps as acutely aware as you say of just the fact that you can become that same situation yourself like you say, it’s my own arrogance that you think you can go on forever feeling just fine. But yeah, I suppose it’s not a bad thing to get a slap in the face from time to time and makes you reappraise things.

Drew: Definitely. Yeah. So I’ve been learning all about optimizing my workspace. What have you been learning about lately?

Ben: Well I’ve got a book that I wrote the first edition of in 2012, the one that you mentioned at the start of the show. And the publishers hassled me every three or four years to do it. Another version of it, which I always grumble and roll my eyes about and I think this is done, like there’s nothing new to add here. But it turns out things move on quite a lot. And I think the majority of my time at the minute has been, I’ve learned a hell of a lot about CSS Grid, which I know Rachel of this parish is a big proponent and has been heavily involved in. And I think the sort of thing that I’ve said to people is that it’s probably, getting a good handle on CSS Grid is probably the biggest upgrade to your CSS skills you can do if you don’t already know Grid. That’s been fantastic.

Ben: And then for the last sort of, I started out like a lot of people my age, I didn’t go into web development as an intention. I find myself there. And so for the longest time I stayed away from what we’d call real programming languages, and it’s only in the last two or three years that I’ve got into JavaScript and TypeScript and so classes and things like that in JavaScript, which I’ve just tried to steer away from the longest time. That’s the stuff I’ve been looking at and trying to really wrap my head around destructuring and all this stuff. There’s no end in sight for learning in web dev world, that’s for sure.

Drew: That is definitely for sure. If you, dear listener, would like to hear more from Ben, you can follow him on Twitter where he’s at. Ben Frane, and find his personal website at benfrane.com. Thanks for joining us today. Ben, do you have any parting words?

Ben: No, just if you wear a wedding ring, maybe think about perhaps not.

(il)
Categories: Web Design

How To Create A Mobile App In Expo And Firebase (For iOS And Android)

Smashing Magazine - Mon, 05/18/2020 - 06:00
How To Create A Mobile App In Expo And Firebase (For iOS And Android) How To Create A Mobile App In Expo And Firebase (For iOS And Android) Chafik Gharbi 2020-05-18T13:00:00+00:00 2020-05-20T10:51:42+00:00

Maybe you’ve heard of or worked with React, the JavaScript framework developed by Facebook. The social media company took it even further by releasing React Native, which quickly became the most popular framework for building mobile apps with JavaScript. Many companies embraced the idea and started building their apps with it.

In this article, we’ll get an idea of how to develop an application for Android and iOS using Expo and Firebase, based on my own experience of creating an application with these technologies. If you haven’t worked with Firebase before, please look at its guide to JavaScript projects before we dive in.

If you are new to JavaScript, make sure you’re clear on the basics of ECMAScript 6’s features, such as class importing and arrow functions. You can learn React Native from the official documentation, which has a section on React fundamentals, in case you haven’t worked with React. Don’t worry about how to build an app with Android Studio or Xcode, because we will be using the Expo framework.

Recommended reading on SmashingMag: Brief Description of Project

We can describe our project as an on-demand transporter — you could say Uber for merchandise transportation. The user will choose transportation information, such as the type of vehicle and loading and unloading locations, and then nearby transportation vehicles will appear on the map. The user confirms their request, and the drivers receive notifications one by one. Each driver’s notification is active for 25 seconds. If they ignore or decline the request, the system selects another driver, and so on. When a driver accepts the request, the user can monitor the entire transportation process on the map, including via the web application.

Expo Installation And Configuration

First, we need to install the command line interface (CLI) for Expo, which will help us test to the app in a simulator or on real devices and to build our app in the cloud.

npm install -g expo-cli

Let’s create our Expo project.

expo init

The cool part is that all of your app’s configurations can be done in a single JSON file, app.json. Below are some tips I learned that could increase your chances of being accepted in the App Store and Google Play and to help you avoid some common problems.

  • If you are using Google Maps in your app, be sure to provide the API in the app.json configuration file, in order to make it work properly. Google won’t charge you for native map rendering unless you’re rendering directions or using other paid API services. ... "ios": { ... "config": { "googleMapsApiKey": "YOUR_API_KEY" } }, "android": { ... "config": { "googleMaps": { "apiKey": "YOUR_API_KEY" } } }
  • To make location updates, or any other background tasks, work in the background in iOS, add the following keys under ios.infoPlist: ... "ios": { ... "infoPlist": { ... "UIBackgroundModes": [ "location", "fetch" ] } }
  • If you don’t define which permissions your app will use, then Expo’s generated app will use all available authorizations by default. As a result, Google Play will reject your app. So, specify your required permissions. ... "android": { ... "permissions": [...], }
  • Apple requires you to provide a message that tells the user why the app is requesting this access, or else you will be rejected. ... "ios": { ... "infoPlist": { ... "NSCameraUsageDescription": "Why are you requesting access to the device’s camera?", "NSLocationWhenInUseUsageDescription": "Why are you requesting access to the device’s camera?" } }
  • Make sure to increment the android.versionCode key before you publish a new version to Google Play.
  • All updates can be done with Expo over the air, without passing by Google Play or the App Store, unless you make the following changes:
    • upgrade the Expo SDK version;
    • change anything under the ios, android, or notification keys;
    • change the app’s splash;
    • change the app’s icon;
    • change the app’s name;
    • change the app’s owner;
    • change the app’s scheme;
    • change the facebookScheme;
    • change your bundled assets under assetBundlePatterns.
  • I prefer not to interpret the user experience by setting fallbackToCacheTimeout to 0 under the updates key. This will allow your app to start immediately with a cached bundle, while downloading a newer one in the background for future use.

And here is a complete example of the configuration in app.json:

{ "expo": { "name": "Transportili", "slug": "transportili", "scheme": "transportili", "privacy": "public", "sdkVersion": "36.0.0", "notification": { "icon": "./assets/notification-icon.png", "androidMode": "default" }, "platforms": [ "ios", "android", "web" ], "version": "0.3.2", "orientation": "portrait", "icon": "./assets/icon.png", "splash": { "image": "./assets/splash.png", "resizeMode": "contain", "backgroundColor": "#ffffff" }, "updates": { "fallbackToCacheTimeout": 0 }, "assetBundlePatterns": [ "\**/\*" ], "ios": { "bundleIdentifier": "com.transportili.driver", "supportsTablet": false, "infoPlist": { "UIBackgroundModes": [ "location", "fetch" ], "LSApplicationQueriesSchemes": [ "transportili" ], "NSCameraUsageDescription": "L’application utilise l’appareil photo pour prendre une photo ou numériser vos documents.", "NSLocationWhenInUseUsageDescription": "L’application utilise votre position pour aider les chauffeurs ou les transporteurs à vous trouver sur la carte." }, "config": { "googleMapsApiKey": "AIzaSyA8Wcik6dTuxBKolLSm5ONBvXNz8Z0T-6c" } }, "android": { "googleServicesFile": "./google-services.json", "package": "com.transportili.driver", "versionCode": 6, "permissions": [ "ACCESS_COARSE_LOCATION", "ACCESS_FINE_LOCATION" ], "config": { "googleMaps": { "apiKey": "AIzaSyA8Wcik6dTuxBKolLSm5ONBvXNz8Z0T-6c" } } }, "description": "", "githubUrl": "https://github.com/chafikgharbi/transportili-native.git" } }

Let’s move on to installing Firebase, using the following command:

expo install firebase

I prefer to create a firebase.js file in the app’s root folder that contains all Firebase configurations. In this case, I’m using only the Firestore and Storage services.

const firebaseConfig = { apiKey: "api-key", authDomain: "project-id.firebaseapp.com", databaseURL: "https://project-id.firebaseio.com", projectId: "project-id", storageBucket: "project-id.appspot.com", messagingSenderId: "sender-id", appId: "app-id", measurementId: "G-measurement-id" };

Now, whenever we want to use Firebase, we just import this file, as follows:

import { firebase, firestore, storage } from "./firebase";

The documentation has a more detailed explanation of using Firebase with Expo.

The Application’s Database

You can store your data directly in the cloud using Firebase, which offers two types of databases. One is the real-time database, and the other is Firestore, which is considered to be the improved version of the real-time database, with more advanced functionality. Both are NoSQL databases with data sync and instant changes listeners. They have different mechanisms: The real-time database stores data as a JSON object, whereas Firestore stores data as documents in collections. They also calculate usage and cost differently: The former is based on the quantity of data exchanged, and the latter is based on the number of operations in the documents (reads, writes, and deletes).

In my case, I used the Firestore database to store users, requests, vehicles, and other application data. (I was trying to be smart by putting all of my data in one document to decrease operation usage, but then I discovered that each document can store only 1 MB.)

In addition to storing strings, numbers, objects, and so on in Firebase, you can also store a geoPoint, which is an object that contains the coordinates of geographic points (latitude and longitude). Despite this, unfortunately, you cannot make geographic queries, such as retrieving nearby users.

To do that, we can use GeoFirestore. But we have to take into account that this package restricts the document structure of the user to this:

User: { d: {all user data here} g: (location geohash) l: {firstore location geopoint} }

So, if you’re going to implement it directly in your user collection, like I did, then you’ll need to put all of the user’s data in the d key.

Last but not least, don’t forget to optimize your code to avoid unexpected operations:

  • Use offline persistence. On the web, offline persistence is disabled; be sure to enable it.
  • Use cursor pagination in Firestore queries. Don’t get all data at once.
  • Always unsubscribe listeners, when done, or unmounted components.
The Application’s Back End

You can manage the Firestore database, send notifications with Expo, and perform certain operations directly from the front end or the mobile application, but there are other operations that we cannot do without a back end and a server. This is why Firebase offers functions — a cloud back end that allows you to execute Node.js code on a scalable server. I’ve used the Firebase functions for the following:

  • Send notifications (see example below)
    To send notifications, we will use push notifications, a tool that helps an app’s owner send messages to their users. It appear in the notifications section of the device, even if the application is not active. We don’t want this process to be stopped by a sudden interruption in connectivity, so we’ll have to use a server.
  • Run cron jobs
    Using cron jobs helps me to manage scheduled requests and notifications.
  • Sanitize the database
    This includes removing useless and ignored requests.
  • Run sensitive, expensive, or continuous tasks
    This includes registering, retrieving users, and scheduling orders. All of these are sensitive operations. If you make them directly from your app or front end, there is a risk of security vulnerability and broken tasks.

Joaquin Cid’s article “How to Build a Role-based API With Firebase Authentication” will give you details on how to get started with Firebase functions and how to create a back-end API using Express. It uses TypeScript, but converting TypeScript to JavaScript is not hard.

Push Notifications

Expo sends a notification to the user’s device from its servers. It identifies the user’s device with a token. When someone uses the application, the app would execute code to obtain the device’s token, and then store this token on the server. I’ve used Firestore as usual to store the token and compare incoming tokens to check whether the user has logged in from another device.

Data to be stored for subsequent push-notification requests. (Large preview)

We get our token using the following function:

token = await Notifications.getExpoPushTokenAsync();

Don’t forget to request permission to push notifications. The documentation has example usage.

Whenever you want to send a notification to this user, you would make a request to Expo’s server, which contains the user’s device token already stored on your server.

curl -H "Content-Type: application/json" -X POST "https://exp.host/--/api/v2/push/send" -d '{ "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]", "title":"hello", "body": "world" }'

The following is a simple example that sends notifications to all users using Firebase functions. This example is not secure. If you want to implement authorization and authentication, please follow Cid’s article mentioned above.

After initializing our project using the Firebase CLI, let’s install the Express framework to handle our API.

npm install express

We need to support CORS and add JSON body-parser middleware. This way, we can make requests from any URL and parse JSON-formatted requests.

npm install --save cors body-parser npm install --save-dev @types/cors

This is the main index.js file of our functions directory:

const express = require("express"); const cors = require("cors"); const bodyParser = require("body-parser"); const admin = require("firebase-admin"); const functions = require("firebase-functions"); // Initialize the firebase-admin SDK module admin.initializeApp(functions.config().firebase); // Set the Express app const app = express(); app.use(bodyParser.json()); app.use(cors({ origin: true })); // Handle push notifications request app.post("/pushNotifications", require("./controllers/pushNotifications")); // Handle another request // app.post("/anotherRoute", require("./controllers/anotherController")); // Export the https endpoint API handled by the Express app export const api = functions.https.onRequest(app);

And this is the pushNotifications.js controller, located in the controllers folder.

const admin = require("firebase-admin"); const axios = require("axios"); const chunkArray = require("./chunkArray"); const firestore = admin.firestore(); async function pushNotifications(req, res) { try { const data = req.body; // Get users from Firestore, then build notifications array await firestore .collection("users").get() .then((querySnapshot) => { if (querySnapshot.size) { // This array will contain each user’s notification let notificationsArray = []; querySnapshot.forEach((doc) => { let docData = doc.data(); if (docData && docData.d) { let userData = docData.d; // The pushNotificationsToken retrieved from the app and stored in Firestore if (userData.pushNotificationsToken) { notificationsArray.push({ to: userData.pushNotificationsToken, ...data, }); } } }); // Send notifications to 100 users at a time (the maximum number that one Expo push request supports) let notificationsChunks = chunkArray(notificationsArray, 100); notificationsChunks.map((chunk) => { axios({ method: "post", url: "https://exp.host/--/api/v2/push/send", data: chunk, headers: { "Content-Type": "application/json", }, }); }); return res.status(200).send({ message: "Notifications sent!" }); } else { return res.status(404).send({ message: "No users found" }); } }) .catch((error) => { return res .status(500) .send({ message: `${error.code} - ${error.message}` }); }); } catch (error) { return res .status(500) .send({ message: `${error.code} - ${error.message}` }); } } module.exports = pushNotifications;

In the controller above, we got all of the app’s users from Firestore. Each user has a push token. We divided this list into sets of 100 users, because a single request to Expo can hold only 100 notifications. Then, we sent these notifications using Axios.

The following is the chunkArray function:

function chunkArray(myArray, chunk_size) { var index = 0; var arrayLength = myArray.length; var tempArray = []; for (index = 0; index < arrayLength; index += chunk_size) { myChunk = myArray.slice(index, index + chunk_size); tempArray.push(myChunk); } return tempArray; }

This is an example of how to send notifications via our API using Axios.

axios({ method: "post", url: "https://...cloudfunctions.net/api/pushNotifications", data: { title: "Notification title", body: "Notification body", }, }); Maps and Geolocation Render Native Google Maps in React Native

To render Google Maps in the mobile application, I used react-native-maps, and to render directions, I used the react-native-maps-directions package. For a web application, I would use pure JavaScript.

npm install react-native-maps react-native-maps-directions

Then, import these packages:

import MapView, { Marker, PROVIDER_GOOGLE } from "react-native-maps"; import MapViewDirections from "react-native-maps-directions";

We’ll render the map with markers and directions:

<MapView style={mapStyle} // Reference is useful for controlling the map like mapView.fitToCoordinates(...) ref={(ref) => (mapView = ref)} // For better performance, avoid using default map on iOS provider={PROVIDER_GOOGLE} // Show the blue dot that represents the current location on the map showsUserLocation={true} initialRegion={{ ...this.state.currentLocation, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }} /* * Watch region change when the user moves the map * for example, to get the address with reverse geocoding. \*/ onRegionChangeComplete={(region) => { console.log( `Map center: latitude: ${region.latitude}${region.latitude} longitude: ${region.latitude}${region.longitude}` ); }} // Map edge paddings mapPadding={{ top: 20, right: 20, bottom: 20, left: 20, }} > {/* Render marker with custom icon \*/} {this.state.marker && ( <Marker title={this.state.marker.title} coordinate={{ latitude: this.state.marker.latitude, longitude: this.state.marker.longitude, }} > <MaterialIcons name="place" size={40} color="green" /> </Marker> )} {/* Render multiple markers \*/} {this.state.markers.map((marker, index) => { return ( <Marker key={index} title={marker.address} coordinate={{ latitude: marker.latitude, longitude: marker.longitude, }} > <MaterialIcons name="place" size={40} color="green" /> </Marker> ); })} {/* Render directions from array of points \*/} {this.state.directions.length >= 2 && ( <MapViewDirections origin={this.state.directions[0]} destination={ this.state.directions[this.state.directions.length - 1] } waypoints={ this.state.directions.length > 2 ? this.state.directions.slice(1, -1) : null } optimizeWaypoints={true} apikey={GOOGLE_MAPS_APIKEY} strokeWidth={5} strokeColor="green" onReady={(result) => { console.log( `Distance "${result.distance} km", "${result.duration} min"` ); }} onError={(errorMessage) => { console.log(errorMessage); }} /> )} </MapView> Watch User’s Location in Foreground and Background

The Expo framework supports background location updates, I want to use this feature to get the user’s position. Even if the app is not in the foreground or the phone is locked, the application should always send the location to the server.

import * as Location from "expo-location"; import * as TaskManager from "expo-task-manager"; import geohash from "ngeohash"; import { firebase, firestore } from "../firebase"; let USER_ID = null; let LOCATION_TASK = "background-location"; let updateLocation = (location) => { if (USER_ID) { firestore .collection("users") .doc(USER_ID) .update({ "d.location": new firebase.firestore.GeoPoint( location.latitude, location.longitude ), g: geohash.encode(location.latitude, location.longitude, 10), l: new firebase.firestore.GeoPoint( location.latitude, location.longitude ), }); } }; TaskManager.defineTask(LOCATION_TASK, ({ data, error }) => { if (error) { // Error occurred - check `error.message` for more details. return; } if (data) { const { locations } = data; // Current position with latitude and longitude currentLocation = { latitude: locations[0].coords.latitude, longitude: locations[0].coords.longitude, }; updateLocation(currentLocation); } }); export default async function watchPosition(userid) { // Set user ID USER_ID = userid; // Ask permissions for using GPS const { status } = await Location.requestPermissionsAsync(); if (status === "granted") { // watch position in background await Location.startLocationUpdatesAsync(LOCATION_TASK, { accuracy: Location.Accuracy.BestForNavigation, distanceInterval: 10, showsBackgroundLocationIndicator: true, foregroundService: { notificationTitle: "Title", notificationBody: "Explanation", notificationColor: "#FF650D", }, }); // Watch position in foreground await Location.watchPositionAsync( { accuracy: Location.Accuracy.BestForNavigation, distanceInterval: 10, }, (location) => { let currentLocation = { latitude: location.coords.latitude, longitude: location.coords.longitude, }; updateLocation(currentLocation); } ); } else { // Location permission denied } }

If you’ll notice, I’ve used different structures when updating the location to Firestore. That’s because I’m using the GeoFirestore package to query nearby users.

Using WebView in React Native

The application is not only for mobile users, but also for desktop users. So, let’s not spend time developing another application that shares much of the same functionality, such as login and registration, profiles and settings, and orders history.

On the app website, we check whether the user came from a desktop browser or the mobile application. We then redirect them to the corresponding application.

For a mobile application, we have to implement some sort of communication between the native app and WebView app, thanks to the JavaScript injection of postMessage and onMessage in WebView. But be careful when and how you use it:

Security Warning: Currently, onMessage and postMessage do not allow specifying an origin. This can lead to cross-site scripting attacks if an unexpected document is loaded within a WebView instance. Please refer to the MDN documentation for Window.postMessage() for more details on the security implications of this.

React Native documentation

We’ll send data from web JavaScript to React Native. Here is an example of sending a user ID:

window.ReactNativeWebView.postMessage( JSON.stringify({ action: "setUserID", data: user.uid }) );

We’ll listen to data coming from the web in WebView.

<WebView ref={(reference) => (webview = reference)} onMessage={(event) => { let message = JSON.parse(event.nativeEvent.data); switch (message.action) { case "setUserID": let id = message.data; break; case "anotherAction": // break; } }} />;

Let’s send data from React Native to the web. The following example sends a location retrieved from React Native.

let location = JSON.stringify({ latitude: 36.742022, longitude: 3.103771 }); webview.injectJavaScript(` window.injectData({ action: "setLocation", data: JSON.stringify(${location}) }) \`);

We’ll read the location on the web:

window.injectData = (message) => { switch (message.action) { case "setLocation": let location = JSON.parse(message.data); break; case "anotherAction": // break; } }; The Web Application and Website

All web-related parts, from the website to the web application, were made with Next.js and hosted on Netlify for three main raisons:

  • cost-effectiveness
    There is no server to maintain, and Netlify’s free plan is more than enough for my needs. Unlimited private repositories are now free on GitHub, so nothing to worry about there.
  • effortless development
    Commit, push, and let Netlify do the rest. Is anything simpler than that?
  • speed
    The websites are static and all hosted on a content delivery network (CDN). When a user requests these websites, the CDN directs them to the nearest copy in order to minimize latency. So, the websites are extremely fast.
Limitations of Expo

There are two approaches to building an app with Expo: the managed workflow, where you write only JavaScript, and Expo tools and services do the rest for you, and the bare workflow, where you have full control over all aspects of the native project, and where Expo tools can’t help as much. If you plan to follow the first approach, then consider Expo’s limitations, because some functionality that exists in major apps, such as Spotify (for example, music playing in the background) and Messenger (call notifications), cannot be done yet.

Conclusion

Expo is an excellent choice if you are not familiar with native development and you want to avoid all of the headaches associated with creating and regularly deploying an application. Firebase can save you a lot of time and work, because of its scalability and variety of services. However, both are third-party services, over which you have no control, and Firestore is not designed for complex queries and data relationships.

Thanks for your attention. I hope you’ve enjoyed this article and learned something new.

(ra, yk, il, al)
Categories: Web Design

Learning Resources In Challenging Times: Online Workshops, Meetups And Events

Smashing Magazine - Fri, 05/15/2020 - 07:30
Learning Resources In Challenging Times: Online Workshops, Meetups And Events Learning Resources In Challenging Times: Online Workshops, Meetups And Events Iris Lješnjanin 2020-05-15T14:30:00+00:00 2020-05-20T10:51:42+00:00

In these current strange times of isolation and social distancing (with almost all events and conferences being cancelled), it can be quite difficult to feel connected to family, friends and colleagues. Here at Smashing, we believe that is is now more important than ever to stay in touch and support each other. Behind the scenes, the team is working tirelessly on ways to keep the community connected, and oh boy do we have a lot of things in store for you! You didn’t really think we’d give up that easily, did you?

Your workplace may look a lot like Topple’s, but even if it isn’t, make yourself comfortable! We’ll help you boost your skills online and learn practical, actionable insights from experts in the industry.

We’ve been busy over the last few weeks, and we’re not stopping yet! We have online workshops, SmashingConf Live, Smashing Meets and last but not least, Smashing TV coming right at your fingertips! But first, let’s see what else we’ve been up to…

Look What’s Cookin’!

Exciting times! Click!, our latest Smashing book, is available for pre-order with a friendly discount — you can already start reading the eBook until your printed copy arrives at your doorstep. Written by Paul Boag and beautifully designed by Veerle Pieters, the book is split into 11 chapters: from exploring the psychology of decision making and how to measure conversion to exploring ways of how to encourage users to act without alienating them.

There is no shortage of books on marketing and UX, but when it comes to bridging the gap between the two, many of us struggle to find the right balance. Pre-order today →

Of course, if you’re feeling smashing today, we’d like to invite you join the Smashing family and get the eBook for free (among with many other eBooks and a few fancy cats!).

Learning And Networking, The Smashing Way

Despite the current circumstances, we’re keen to find ways in which we can offer Smashing experiences to anyone interested in learning from experts in our industry — without needing to leave your desk! We’ve been asking what type of resources you’d like to have, and so all of the following online events is what has landed in our Smashing wishing well. Thank you to everyone who has shared their thoughts and feedback — we’ve been all ears!

1. Online Workshops (May–July)

Our friendly online front-end/UX workshops are bound to boost your skills and help you gain practical, actionable insights from experts in the industry — live. There will be plenty of insightful takeaways, exercises, slides, recordings and friendly Q&A time. Of course, we’re happy to provide discounts for large groups and students.

We already have you covered for the next three months — make sure to save your spot as soon as you can:

When? What? Who? May 7–22 Advanced CSS/Sass Miriam Suzanne May 12–26 Smart Interface Design Patterns Vitaly Friedman May 28 – June 12 Web Performance Masterclass Harry Roberts June 11–12 The CSS Layout Masterclass Rachel Andrew June 16–30 Front-End Accessibility Masterclass Marcy Sutton June 18–26 Building Modern HTML Emails Rémi Parmentier July 2–17 Buy! The eCommerce UX Workshop Vitaly Friedman July 7–21 Design Systems Brad Frost

Note: If you’re also interested in how you too can run online workshops, listen to Smashing Podcast episode 14 with Rachel Andrew in which she talks about running online workshops and how a traditional event can adapt when participants can’t attend in person.

2. SmashingConf Live (June 9–10)

Meet SmashingConf Live (June 9–10), a truly smashing, friendly online conference on front-end & UX. With interactive live sessions, practical insights, accessible speakers, collaborative notes and fireplace chats with like-minded folks. Jump to first confirmed speakers. Check schedule  →

Both days start at 8 AM PDT (check your time), with interactive sessions, followed up with a time for Q&As and discussion zones.

Ah, and the best bit: a conference in which you play an active role — taking part in live sessions, Q&As, discussion zones and challenges. To the schedule. But of course that’s not all! Be prepared for design & coding challenges, scavenger hunt and fireplace sessions with mystery guests. And to keep in style, of course we’ll throw a Smashing Party.

Do you like what you see, but are worried about getting some time off from work? Well, you surely didn’t think we would leave your hanging? We know how difficult it can sometimes be, and so we’ve prepared a neat lil’ Convince-Your-Boss template to help you out. Good luck!

3. Smashing Meets (Free) We’re super excited to run our very first Smashing meetup next week! We will focus on front-end and UX, but also cover all sorts of topics from performance to accessibility. Smashing Meets wouldn’t be possible without some amazing communities from around the world, so another Thank You to everyone involved!

4. Smashing TV (Free Webinar on May 19th) Looking for ways to help you expand your accessibility test coverage beyond automation? With very little resources, you can make a meaningful difference. Join us with Carie Fisher and Harris Schneiderman at 7:00 PM CET/1:00 PM EDT who will demonstrate the basics of automated testing and share key lessons on on maximizing your accessibility impact.

Sharing Personal Experiences And Stories

We’re moving onto our 16th episode of the Smashing Podcast next week! The Smashing Podcast is the perfect way to take a little bit of Smashing along with you on your morning walks, while washing the dishes, or anytime you like really. You can subscribe in your favorite app to get new episodes as soon as they’re ready.

Your Design Work Deserves Attention

Do you have artwork you’d love to share with the design community? If so, please do! We are always looking for creative talent, so if you have an idea for a wallpaper design, please don’t hesitate to submit it. Join in! →

Trending Topics On Smashing Magazine

We publish a new article every day on various topics that are current in the web industry. Here are some that our readers seemed to enjoy the most and have recommended further:

  • Setting TypeScript For Modern React Projects Using Webpack And Babel
    by Blessing Krofegha
    This article introduces Typescript, a superscript of JavaScript that presents the static type feature for spotting common errors as developers codes, which enhances performance, hence results in robust enterprise applications. You’ll also learn how to efficiently set up TypeScript in a React Project as we build a Money Heist Episode Picker App, exploring TypeScript, React hooks such as useReducer, useContext and Reach Router.
  • A Complete Guide To Mechanical Keyboards
    by Ben Frain
    How much thought have you put into your primary input device? Ever considered how much better your interface with your computer might be? In this article, we dive into the possibilities of mechanical keyboards. The different layouts, switch types and even keycap material. Strap yourself in — this will be a deep dive!
  • Micro-Typography: How To Space And Kern Punctuation Marks And Other Symbols
    by Thomas Bohm
    For hundreds of years, we have been using white space in typography. Today, in 2020, how do we add spacing to punctuation marks and other symbols, and how do we adjust the space on the left and right side in an easy and consistent way? It is actually not as easy and quick as it should be.
  • How To Pass Data Between Components In Vue.js
    by Matt Maribojoc
    With so many different ways to share data across components, you should know which technique is best for your situation. Let’s analyze three of the most common ways to pass data in VueJS.
  • Reducing Design Risk
    by Eric Olive
    The pressure to rush market and usability research carries risk. We’ll offer four practical techniques to mitigate this risk and create designs that better serve customers and the company: context over convenience, compromise, better design decisions, design reduction.
Best Picks From Our Newsletter

We’ll be honest: Every second week, we struggle with keeping the Smashing Newsletter issues at a moderate length — there are just so many talented folks out there working on brilliant projects! Kudos to everyone involved!

Interested in sponsoring? Feel free to check out our partnership options and get in touch with the team anytime — they’ll be sure to get back to you right away.

P.S. A huge thank you to Cosima Mielke for writing and preparing these posts!

Creating Accessible Color Palettes

Finding the perfect tint or shade of a color is not only a matter of taste but also accessibility. After all, if color contrast is lacking, a product could, in the worst case, even become unusable for people with vision impairments. A very detailed contrast checker to help you detect potential pitfalls ahead of time comes from Gianluca Gini: Geenes.

The tool lets you tinker with hue ranges and saturation and apply the color palettes to one of three selectable UI mockups. Once applied, you can trigger different kinds of vision impairments to see how affected people see the colors and, finally, make an informed decision on the best tones for your palette. To use the colors right away, just copy and paste their code or export them to Sketch.

Command Line Love

It’s not uncommon for technical documentation to be dry and feel intimidating, especially for people who are just getting started with a new tool. That can get quite frustrating especially when a manual is difficult to read or follow, or the explanations are verbose and lack examples.

Dash Dash takes the Unix (Linux, BSD, macOS) open source manual pages and sets the content in a beautiful type and layout. It provides not only explanations of all commands, but also search, examples and TL;DR sections. Also, The Art of Command Line takes you on a journey to Command Line from basics to system debugging.

And if you are up for advanced command line techniques, cmdchallenge prompts you to solve tasks with a single line of bash. (vf)

Accessible Component Libraries

While many of the component libraries we create are trying to cover all the usual suspects (the accordions, the tables, the carousels, the drop-downs, along with typography, colors and box shadows), No Style Design System by Adam Silver is focused primarily around accessibility and web forms.

As a system created for and used in his book on Form Design Patterns, Adam’s library provides a set of accessible components for everything from autocomplete, checkboxes and password reveal to radios, select boxes and steppers. Most of them have a minimal CSS styling with clean, accessible markup. And if you need slightly more advanced components, Heydon Pickering’s Inclusive Components has got your back: with comprehensive tutorials on accessible cards, data tables, notifications, sliders, tabbed inerfaces, tooltips, menus and toggles. (vf)

Custom CSS Cascades

Miriam Suzanne built a demo to illustrate a very clever way to define a cascade of custom properties. One that allows you to determine which intent should take priority, without worrying about the specificity of how the value is defined.

See the Pen [Custom Cascades](https://codepen.io/smashingmag/pen/JjYawPP) by Miriam Suzanne.

See the Pen Custom Cascades by Miriam Suzanne.

Miriam shows how it works at the example of a button. Due to how the cascade is arranged, the default button is always falling back to --btn-bg--default. Adding the disabled attribute, always overrides any other button colors, no matter where they are defined, and, when new button types are created, --btn-bg--type ensures that only the defaults are overridden but not the state. The approach also lets you set these values contextually. A smart solution to avoid the usual dangers that highly-specified inline styles usually bring along.

Front-End Bookmarks

Some of us save all the useful articles and talks they come across in one ever-growing bookmark folder (which can make finding what you’re looking for quite a challenge at times), others have a more organized approach. Like Manuel Matuzović.

Manuel collects articles and talks about HTML, CSS, and JavaScript on his site Front-End Bookmarks, grouped alphabetically by elements, attributes, properties, selectors, methods, and expressions. No matter if you’re looking for information on how to correctly use aria-labelledby or what the ::marker pseudo-element is all about, chances are good that Manuel already compiled helpful resources on the topic. By the way, if you feel that a resource is missing in the collection, don’t hesitate to contribute to it on GitHub.

GitHub Tips And Tricks

Do you know how to automatically squash commits on GitHub when merging pull requests? Or how to open a repo in the browser using GitHub CLI? If not, Joe Previte’s collection of GitHub tips and tricks might be for you.

In bite-sized videos, Joe shares small but powerful tips to take your GitHub workflow to the next level. And for those of you who prefer to learn by reading, most tips are also available as short blog posts. Handy little timesavers.

The Sound Of Colleagues

Working from home can have some real advantages over working from an office, but let’s be honest, it can be a rather lonely experience, too, when there are no colleagues around. If you feel your home office is getting too quiet and you need some bustle in the background to stay focused, The Sound of Colleagues has got your back.

The Sound of Colleagues lets you mix office noises to create your custom office ambient noise. People typing and talking, phones ringing, the coffee machine, the printer — all of these little things add up to bring a bit of office feeling to your home. Maybe it’ll even help you boost your productivity, who knows?

A Minimalist And Modern Media Player Library

If you want to embed a media player on your site, Vime might be worth taking a closer look at. Built around the idea that you control the player, not the other way around, the open-source library provides an alternative to Videojs and Plyr and supports HTML5, HLS, Dash, YouTube, Vimeo, and Dailymotion.

Vime does not only shine with a minimalist, sleek look, but it is responsive, accessible, modular, and lightweight, too. It gets by without any external dependencies and comes in different packages tailored to different needs so that you can pick just what’s required for your use case. And since minimalist doesn’t mean bland, Vime is backed up by a plugin system that offers a lot of room for customization — think custom controls, settings, tooltips, and more. The last two versions of all modern browsers as well as IE11 are supported.

Smashing Newsletter

Every second Tuesday, we send a newsletter with useful techniques on front-end and UX. Subscribe and get Smart Interface Design Checklists PDF in your inbox.

Your (smashing) email Subscribe → Front-end, design and UX. Sent 2× a month.
You can always unsubscribe with just one click. (cm, vf, ra)
Categories: Web Design

Accessible Images For When They Matter Most

Smashing Magazine - Fri, 05/15/2020 - 02:30
Accessible Images For When They Matter Most Accessible Images For When They Matter Most Carie Fisher 2020-05-15T09:30:00+00:00 2020-05-20T10:51:42+00:00

When it comes to informing the public about critical health issues, timing is everything. The information you consume today could save your life tomorrow. And with more than 65% of the population being visual learners — meaning they learn and remember best through visual communication — the job of creating and sharing accessible images has never been more important. This is especially true for public service announcements (PSAs) aimed at providing crucial and urgent information to the public.

But what happens when your users have visual impairments? Or dyslexia? Or cognitive disorders? How do they receive and understand this visual information? What elements make an image accessible or inaccessible?

Image Types And Alts

Before we dissect an image and examine each element that can make or break its accessibility, we first need to take a step back and think about the purpose of the image. Is it to inform a user? Elicit an emotion? Is the image acting as a link? Or is it purely eye-candy?

There are a number of questions that can help you determine how best to convey the image information to a person using an assistive technology (AT) device, like a screen reader.

“What type of message is the image trying to convey?”

“Is the message simple, complex, emotional, or actionable?”

Using a tool such as an online image decision tree or the simplified chart shown below can help you decide which category your image belongs to. Or just imagine your image has — poof! — vanished. Then ask yourself:

“Do I understand the content that remains?”

If the answer is yes, it is decorative. If not, the image is informative and contextually necessary. Once you determine what kind of image you are working with, there are some basic accessibility guidelines to consider.

Image alt flow chart (Large preview) Decorative Images

If you decide your image is decorative, then programmatically the image needs to be hidden. One way to do this is to use an empty/null alternative text attribute. This sends a signal to the AT devices to ignore this image as it is not needed to understand the content or action on the page. There are many ways to hide alternative text including using an empty/null alt (e.g. <img alt="">), using ARIA (e.g. <img role="presentation">, <img role="none">, or <img aria-hidden="true">), or by implementing the image as a CSS background.

Note: An empty/null alternative text attribute is not the same as a missing alternative text attribute. If the alternative text attribute is missing, the AT device might read out the file name or surrounding content in an attempt to give the user more information about the image. While aria-hidden="true" is an option to hide images, be cautious where you apply it as it will remove the entire element from the accessibility API.

In the example below, we see a giant letter “S” and a drawing of a black cat with green eyes used to make the drop cap look a bit more fun on a Smashing Magazine article.

Article screenshot with S drop cap and cat illustration (Large preview)

When we remove the drop cap illustration, what changes? Certainly, there are visual differences, but no information is lost.

Article screenshot without a drop cap or illustration (Large preview) <div class="drop-caps" aria-hidden="true"> <img src=".../images/drop-caps/s.svg" alt=""> <img src=".../images/drop-caps/character-12.svg" alt=""> </div>

In this drop cap example, both aria-hidden="true" and an empty/null alt <img alt=""> were used to hide the images from assistive technology devices. While this kind of redundancy is not necessary to make it accessible — it is also not harmful in this particular situation since the drop caps <div> does not contain any additional information we would need to expose to an AT user. Just remember: when it comes to accessible code, more is not always better.

Beyond programmatically hiding your image — there is not much more you need to consider when it comes to decorative images. If you are saying “But wait, what about X?” or “How about Y?” then you might need to go back to the image decision tree tools and re-evaluate your image — it might not be 100% decorative after all. One of the most difficult types of images to categorize tends to be the “emotional/mood” based images since this subtype is a bit subjective. What one person considers decorative another person might consider informative, so use your best judgment.

Informative Images

If you decide your image is informative, there are a lot more things to consider. For AT devices to understand the message or intent of an image, informative images must have programmatically-discernible alternative text. Typically, this is accomplished using the alt="[some description]" method, but there are many alternative ways to add image information depending on its subtype, type of image, and context (e.g. complex vs simple, SVG vs img). But having alternate text is not enough — it must also be meaningful. For example, if your image is about feeling safe at home, but your alternative information says “house” — does that convey the full message?

An example of an informative image is the following Smashing Magazine logo. If we ask the same question as before (does the context or content change if this image is missing?), then the answer is “yes.” In this example, the logo is both informative and actionable since it is both an image and a link. We can see from the code snippet that <a title="Back to the homepage"> is the link title and the image alternative text is <img alt="Smashing Magazine">. When we fire up an AT device — like a screen reader — we should hear both pieces of information conveyed.

Smashing Magazine logo (Large preview) <div class="logo"> <a href="/" title="Back to the homepage"> <picture> <source media="(min-width: 1350px)" srcset=".../images/logo-full.svg"> <img src=".../images/logo/logo.svg" alt="Smashing Magazine"> </picture> </a> </div>

Hearing both the phrase “back to the homepage” and “Smashing Magazine” in one feature is OK since each phrase is unique and connected to a different purpose.

For more complex alternative text phrases, conduct the telephone test. For example, if you called up a friend and said “purple slug” and hung up the phone your friend would probably be confused, but also might think of a purple slug — but in what context? If you called a friend and said “the purple slug is eating my hydrangeas,” that would paint a more vivid picture — without adding a lot of additional characters or effort.

Of course, an AT user will have to listen to your alternative text, so don’t go overboard. That is why it is suggested to cap your text at 150 characters. If you need to add more context to the image (e.g. complex image), there are other, more descriptive patterns or methods you can use to add more detail.

World Beyond Image Alts

Now that we covered image types and alternative text attribute basics, let’s look beyond and consider some additional image elements:

In each real-world PSA example, we will look at the image through the lens of a different type of disability — keeping in mind that simulators are tools and may not represent an individual’s true experience. Yet, by using such tools, we can begin to build empathy into our designs and really consider the different ways our images are being consumed.

Note: To be clear, the following examples are for illustrative and educational purposes only and not meant to call-out or otherwise pass judgment about the designs in question. Also, there may be multiple issues in one PSA, but we will just focus on one issue type per example. There will be a lot of opportunities for improvement in the area of digital communications when the dust settles on COVID-19 and accessibility is just one more area to consider reviewing.

Color And Contrast

The beating heart of design arguably is color, and if color is the heart of design, then contrast is the muscle. Without good color contrast levels in place elements like words, icons, and other graphical shapes are hard to discern and the design can quickly become inaccessible. But what happens when you perceive color and contrast differently than others — does the same message and intent come through? How can we reach people with color-sensing issues? Color blindness — is a real concern for accessibility-focused designers.

Who Color And Contrast Can Affect
  • It is estimated that 300 million people worldwide are color blind, and approximately 95% of those inflicted are male (1 in 12 men vs 1 in 200 women are color blind). There are many different variants of color blindness, with red/green color blindness being the most common, followed by blue/yellow, and total color blindness being the most rare.
  • Globally there are 246 million people with low vision. People with visual impairments such as glaucoma, cataracts, macular degeneration, diabetic retinopathy, corneal clouding, etc, may have issues with text contrast. People with partial sight and older adults also often experience limited color vision.
  • People using monochrome displays or in certain situations (e.g. low lighting in a room) might have trouble with contrast. People using text-only, limited-color stylesheets, or in certain situations (e.g. too much glare on a screen) might have trouble discerning colors, too.
PSA Color Review

In the first example, we are reviewing PSAs from the non-profit group called the Ad Council — one of the oldest and most prolific producers of such material in the US. The aim of these “higher risk assets” is to reach populations considered more susceptible to contracting and becoming seriously ill by the novel coronavirus (one of the groups that need this information the most).

First, we see the unedited version of the PSAs:

Original CDC + Ad Council PSAs on COVID-19 (Large preview)

Next, we can see two types of color blindness simulated using the ChromeLens extension. ChromeLens is a Google Chrome extension that provides a suite of tools to help with web accessibility development and includes the Lens Vision Simulator, which transforms the colors on a website simulating what a colorblind person might see.

Simulated PSA with Deuteranopia (red/green-blindness):

PSA with Deuteranopia (red/green-blindness) color filter applied (Large preview)

Simulated PSAs with Protanomaly (red-weak):

PSAs with Protanomaly (red-weak) color filter applied (Large preview)

Below is a breakdown of some color contrast ratios found on the PSAs between the different color blindness simulators.

Original PSA — color contrast ratio of 1.26:1 with the text “Have” against the background:

Original PSA – color contrast ratio of 1.26:1 with the text “Have” against the background (Large preview)

Deuteranopia simulation filter applied — color contrast ratio of 1.07:1 with the text “Have” against the background:

Deuteranopia simulation filter applied – color contrast ratio of 1.07:1 with the text “Have” against the background (Large preview)

Protanomaly simulation filter applied — color contrast ratio of 1:15:1 with the text “Have” against the background:

Protanomaly simulation filter applied – color contrast ratio of 1:15:1 with the text “Have” against the background (Large preview)

While these PSAs incorporate a variety of striking color choices and are visually appealing (when testing the text against the background in these images), many of the combinations do not pass the Web Content Accessibility Guidelines (WCAG) color contrast ratios. This is true even for the unedited versions of these designs, but when we apply the ChromeLens color blindness simulator for Deuteranopia (red/green-blindness) Protanomaly (red-weak), the color contrast ratios get even worse (1.26:1 vs 1.07:1 and 1:15:1). To make these PSAs more accessible, we would want to bump up the contrast so people with color-related vision disorders could read the text.

PSA Contrast Review

Going back to the “higher-risk assets” from the Ad Council, we can see how the PSAs look like to people in two different low vision situations.

First, we see the unedited version of the PSAs:

Original CDC + Ad Council PSAs on COVID-19 (Large preview)

Next, using the NoCoffee Vision Simulator tool, we can see how the PSAs might look to someone with low vision and cataracts.

PSAs with simulated low vision filter applied:

PSAs with simulated low vision filter applied (Large preview)

PSAs with simulated cataract filter applied:

PSAs with cataract filter applied (Large preview)

Below is a breakdown of some color contrast ratios found on the PSAs between the different low vision simulators.

Original PSA — color contrast ratio of 1.33:1 with the word “Undergoing” against the background:

Original PSA – color contrast ratio of 1.33:1 with the word “Undergoing” against the background (Large preview)

PSA with low vision simulation filter applied — color contrast ratio of 1.25:1 with the word “Undergoing” against the background:

PSA with low vision simulation filter applied – color contrast ratio of 1.25:1 with the word “Undergoing” against the background (Large preview)

PSA with cataract simulation filter applied — color contrast ratio of 1.06:1 with the word “Undergoing” against the background:

PSA with cataract simulation filter applied – color contrast ratio of 1.06:1 with the word “Undergoing” against the background (Large preview)

A lot of people blame color for their design accessibility issues, but these examples show that contrast plays a key role as well. Without changing the colors on these PSAs, but by changing the user perspective and blurring or obfuscating the text, we can see that the text on the images is more difficult to read — even though the contrast ratios didn’t change by much (1.33:1 vs 1.25:1 and 1.06:1). Similar to the color examples (to make these PSAs more accessible), we need to increase the contrast on these images so people with low vision and eye disorders could read the text.

Next Steps For Accessible Color And Contrast

Review the WCAG color contrast ratio guidelines and use tools like the Colour Contrast Analyser to check your designs. Your images with copy need a color contrast ratio of at least 4.5:1 for regular-sized text, and at least 3:1 for large-sized text (18pt and larger). The color contrast ratio of 3:1 also applies to essential icons. Try a tool like the A11y Color Palette where you can quickly review all the possible accessible color combinations and create a palette with accessibility in mind. Or use the accessibility features built-in into the palette generator Coolors.

Next, utilize solid color backgrounds (reading text on busy backgrounds, overlays, textures, or gradients is difficult in general), but especially when the text does not have enough contrast. By picking colors on the opposite ends of the color spectrum and avoiding red/green and blue/yellow combinations, you will increase the likelihood that your color and contrast ratios are robust. Use a tool like the ChromeLens extension to double-check the color contrast with color blindness in mind. Also, be careful with light shades of color — especially grays — they are difficult to see for people with low vision. Use tools like NoCoffee Vision Simulator to simulate low vision issues and see how your design holds up in these situations.

Going beyond color contrast ratios, it is also important to not use color alone to convey information. For example, “contact information can be seen in red” or “click the blue button to learn more.” The same is true for sensory characteristics such as shape, color, size, visual location, orientation, or sound — they cannot be used on their own. For example, if you said "Please click the link to the left of the image for more information," an AT user could have difficulty finding the correct link.

Typography and Layout

In a perfect world, we would keep our text and images separated. This would allow users to manipulate the typography and layout in any way they would want: font size, letter spacing/kerning, justification, margins/padding, and more. But unfortunately, there are a lot of formats that this kind of separation is difficult or impossible, such as social media posts, emails, PDFs, and other fixed form media.

Who Typography And Layout Can Affect
  • Typography is especially important to the estimated 15–20% of the world’s population with dyslexia — a learning disorder in which certain letters, numbers, or combinations of letters can be confusing or seem to flip/move around.
  • People with low vision can have issues with tight letter spacing/kerning, morphing words like “barn” into “bam” or “modern” into “modem” while reading.
  • For people with attention-deficit disorders and reading or vision-based disabilities, a complex layout is a real barrier. These users have trouble keeping their place and following the flow of the content due to the lack of whitespace and clear linear pathways.
PSA Typography And Layout Review

Let’s first take a look at a PSA from California’s Long Beach Health and Human Services.

If we are looking at this PSA from an accessibility point of view, what typography and layout issues do you see? In what ways could we improve this image?

Original PSA:

PSA from Long Beach Health and Human Services (Large preview)

Unedited PSA with mark-up and notes:

PSA from Long Beach Health and Human Services marked up with accessibility design notes (Large preview)

If we focus on the typography and layout the following elements stand out:

Red hand-drawn lines Illustrating the multiple “rivers of space” created by the justified alignment. Blue dotted boxes Outlining six different layout changes. Pink numbers Highlighting the 14 different typography treatments discovered (ignoring the logo). Some changes are more obvious like font family or color changes, some are more subtle like alignment, size, or weight changes in the typography. Green question marks What does this equation even mean? Cognitively this is a difficult thing to ascertain given the odd layout. Black lines and dots Expected 12 points of visual interest in an UX eye-tracking test based on the order of the content blocks (top to bottom, left to right) and typical equation flow (X + Y = Z).

Let’s look at another PSA and again evaluate the typography and layout from an accessibility point of view. This time, the image was created by the Health Department of Prince George County in Maryland.

Original PSA:

PSA from the Health Department of Prince George County (Large preview)

Unedited PSA with mark-up and notes:

PSA from the Health Department of Prince George County marked up with accessibility design notes (Large preview)

If we focus on the typography and layout the following elements stand out:

Blue dotted boxes Outlining nine different layout changes. Green numbers Highlighting the 11 different typography treatments discovered (ignoring the logos). Some changes are more obvious like font family or color changes, some are more subtle like alignment, size, or weight changes in the typography. Black lines and dots Expected 10 points of visual interest in an UX eye-tracking test based on the order of the content blocks (top to bottom, left to right) and numbering order (1 to 6) forming a zig-zag type eye movement.

So far we’ve seen some examples where there are a lot of typography changes and the layouts are complex. Now, let’s review a cleaner PSA. This one is from the Prevention Action Alliance out of Columbus, Ohio.

Original PSA:

PSA from the Prevention Action Alliance (Large preview)

Unedited PSA with mark-up and notes:

PSA from the Prevention Action Alliance marked up with accessibility design notes (Large preview) Blue dotted boxes Outlining three different layout changes. Pink numbers Highlighting the four different typography treatments discovered (ignoring the logos). In this case, only one font family was used, with variations only on size, color, and weight. Black lines and dots Expected eight points of visual interest in an UX eye-tracking test based on the order of the content blocks (top to bottom).

The third PSA example is more consistent when it comes to typography and layout, and has more overall whitespace and a linear visual pathway compared to the first two examples.

Next Steps For Accessible Typography And Layout

Less is more when it comes to accessible typography, so limit the number of different font families and variations such as italic, bold, ALL CAPS, or other styling methods that may make the content difficult to read. The research is not conclusive about whether serif or sans-serif typefaces are easier to read, but if you choose font families that have clearly defined letter shapes it is more likely that the font will be accessible. Some common offenders to look out for when choosing an inclusive font include the “I” (ex. India), “l” (ex. lettuce), and “1” (ex. one). Likewise, characters like “b” and “d” and “q” and “p” can sometimes be mirrored (either left-right or up-down), and the letter “B” and the number “8” oftentimes look too similar.

In regards to layout, less is also more. Try and repeat patterns whenever possible and limit the width of any blocked section to 80 characters (or 40 characters for logograms). Likewise, avoid paragraph alignment which creates whitespace or “rivers of space” within the content (e.g. justified alignment). Line spacing (leading) is at least space-and-a-half within paragraphs, and paragraph spacing is at least 1.5 times larger than the line spacing. Incorporating all of these layout guidelines will help people with attention-deficit disorders, reading and vision-based disabilities focus more on the content.

Copy And Icons

Last but not least, let’s focus on the actual PSA message. Arguably, copy is the key element in informing the public on the latest COVID-19 updates and providing information about preventing the spread of the virus. But icons in this situation serve up more than just decoration; these elements visually repeat the same message as the copy. No pressure, but both copy and icons need to be spot-on to reach the widest array of people.

Who Copy and Icons Can Affect
  • People with attention-deficit disorders — estimated at 129 million people worldwide — can have issues focusing on copy that is too long, does not break items into lists, and lacks whitespace (think: line height, paragraph margins, etc).
  • For people with certain cognitive disabilities, it is difficult to understand figurative language or specialized usage like the phrases “it’s raining cats and dogs” or “that test was a piece of cake.”
  • People with cognitive, language, and learning disabilities may need visual icons, graphics, and symbols to understand the accompanying copy.
PSA Copy Review

For this example, let’s test the copy of two PSAs from the Centers for Disease Control and Prevention (CDC) for readability. Readability is the ease with which a reader can understand a written text. Readability of copy depends on both the content and presentation.

CDC created PSA — What you should know about COVID-19 to protect yourself and others:

CDC created PSA – What you should know about COVID-19 to protect yourself and others (Large preview)

If we evaluate the main body copy using readability indicator tools like Readable and The Readability Test, we see that the “What you should know about COVID-19 to protect yourself and others” PSA has 388 words at an average reading grade level of 9 and a Flesch Kincaid Reading Ease1 of 64.6. In addition to those metrics (for accessible copy), we also want to look at the number of complex words and their frequency — in this case, 35 and 9.02% respectively.

1 The Flesch Kincaid Reading Ease level is out of 100. The lower the number, the more difficult the copy is to read. For reference, a reading ease score of 60-70 is considered acceptable for basic web copy.

Test results for the PSA – What you should know about COVID-19 to protect yourself and others (Large preview)

While the copy in the first image was adequate and falls in the suggested readability ranges for web-based copy, let’s compare it to another PSA created by the CDC on the same subject.

CDC created PSA — Stop the Spread of Germs:

CDC created PSA – Stop the Spread of Germs (Large preview)

This PSA has a lot more imagery and a lot less text. If we again evaluate the main copy, we see that our copy now has a total of 90 words with an average grade of 6 and a Flesch Kincaid Reading Ease of 83.6. The number of complex words is now down to 4 with a frequency of 4.44%.

Test results for the PSA – Stop the Spread of Germs (Large preview)

Compared to the first PSA, the “Stop the Spread of Germs” PSA one has 298 fewer words and is easier to read by 3rd-grade levels. It has a reading ease level increase of 19 points, and is less complex. Based on these numbers, we can extrapolate that the second PSA is more inclusive than the first when looking at copy alone.

PSA Icon Review

But testing the readability of copy isn’t the only way to measure the effectiveness of a PSA when it comes to message accessibility. Another element we need to look at are the icons accompanying the copy. If we are presented only the icons, will the same message be received?

Let’s now look at a couple of examples. Based on the icons alone, what is the message that the image is trying to convey about riding your bicycle safely during COVID-19?

Edited PSA from the European Cyclists’ Federation:

Edited PSA from the European Cyclists’ Federation (Large preview)

Original PSA:

Original PSA from the European Cyclists’ Federation (Large preview)

This is the unedited PSA. Were you able to figure out the full message? While you might have been able to guess correctly for a couple of icons, were there parts of the message you missed not having the copy?

OK, let’s take a look at another example. This next PSA comes from the Pennsylvania Department of Health. Let’s do the same exercise as before: can you understand the message in this PSA (without the icon copy)?

Edited PSA:

Edited PSA from the Pennsylvania Department of Health (Large preview)

Original PSA:

Original PSA from the Pennsylvania Department of Health (Large preview)

Now we can see the PSA with copy. Were you able to figure out the full message? While there may have been an icon or two that tripped you up, was it easier to decipher the icons on the second PSA versus the first? Hopefully, this quick exercise helped you understand the critical role icons play in the message.

Next Steps for Accessible Copy and Icons

Be clear and concise. The unofficial rule of thumb is to write for a 9th-grade reading level. This level is based on the assumption that most people reach the 12th-grade reading level, but in times of peak stress, they might not be reading at their highest level. Try and use plain language and avoid technical jargon, fancy words, colloquialisms, and expressions. Likewise, make sure any acronyms, abbreviations, or unusual words are explained in more detail or linked out to additional resources. Tools like Readable and The Readability Test can help you determine the reading level of your copy, while tools like Hemingway Editor or Grammarly can suggest edits to make your copy more inclusive.

Use icons, graphics, and symbols to supplement copy whenever possible. Adding imagery allows you to break down some language and cognitive barriers and not rely on your typography to carry all the weight. Just be sure to choose icons that are common or don’t require a lot of thought.

Wrapping Up

Creating accessible images involves a lot more than just adding alt text. It is important to consider how all image elements — color, contrast, typography, layout, copy, and icons — affect your users as well. By taking a bit more time and building these accessibility principles into your images you will undoubtedly reach more people — on their terms. In uncertain times like these, we need to be sure we are addressing all the ways we can improve our images to be more inclusive in our messaging.

(ra, yk, il)
Categories: Web Design

10 Best Responsive HTML5 Sliders for Images and Text... and 3 Free Options

Tuts+ Code - Web Development - Thu, 05/14/2020 - 07:50

In this post, I'll show you some of the best free and paid HTML5 sliders. We'll see responsive text sliders, responsive image sliders with text, banner sliders, and more. All built with HTML5 and CSS.

Why Use a Responsive HTML5 Slider?

HTML5 enables users to have a better and more consistent web experience across several devices. Now that smart devices are the number one way that people access the web, your site needs to be responsive. That is, it needs to work on varying screen sizes and resolutions—from a smartphone right up to a full-size computer.

A professional, responsive HTML5 and CSS slider will look great and work great on all these devices. If you have image-rich content or want to present key text in an interesting way on your website, then you just can't go wrong by using an HTML5 slider.

HTML5 Sliders on CodeCanyon

There are currently over 230 premium HTML5 based content sliders available on CodeCanyon. You can start using them on your website right away. Once you purchase a plugin, you will be eligible for free lifetime updates and six months of free support.

The large variety of scripts, widgets, and plugins available in the market should meet almost all your needs. You can use them to create sliders for your most popular posts, your best products, or customer testimonials. They are easy to use and look great on all devices.

The Best HTML5 Sliders on CodeCanyon for 2020

Because there are so many sliders out there to choose from, I've pulled together a list of the ten best HTML5 sliders for images and text available at CodeCanyon.

1. Ultimate 3D Carousel

If you’ve ever seen or used an actual slide carousel, you’ll appreciate the design and aesthetics of the Ultimate 3D Carousel. This carousel slider allows you to display multimedia content with a unique 3D layout that mimics the carousels of film photography days. 

There are a number of effects you can apply to your carousel style if you choose, and if you prefer a more traditional slide effect, you can also opt for that instead of the carousel style.

The carousel supports images, MP4 videos, MP3 audio, Google Maps, and more. It runs on all major browsers and uses a responsive layout with auto-scale function so that it works well on all mobile devices.

2. Simple 3D Coverflow

Simple 3D Coverflow is a fully 3D multimedia slider plugin. You can use the plugin to display multimedia content on the website in an original and catchy layout that uses 3D perspective.

You can include all kinds of content in a single slide. This includes images, videos from YouTube and Vimeo, etc.

Here are some of its awesome features:

  • responsive image slider with text that looks great on mobiles as well as desktops
  • navigation support for mouse wheel and the left/right arrow keys on the keyboard
  • ability to classify thumbnails into categories in a slideshow
  • two skins, with nine different layouts for each of them

The plugin comes with the Revolution lightbox, which can display all kinds of content like images, videos, iFrames, Google maps, etc.

Make sure you go and see the live preview of this fantastic plugin.

3. Creative BS-4 Carousel Slider

This slider is ideal for anyone who is already using Bootstrap 4 on their website. The framework already provides a lot of features and capabilities. It makes sense to take advantage of this fact and create a multi-functional slider.

This is a fully responsive HTML5 slider and has great cross-browser compatibility.

You will be getting 33 different carousels with their own animations. This plugin can create carousels for everything from products to testimonials and portfolios to video carousels.

The live preview of the plugin covers all these use cases, so do check it out.

4. Vertical Ultimate 3D Carousel

This ultimate vertical 3D carousel offers a unique solution when it comes to sliders and carousels. Instead of presenting the carousel content horizontally, the slides are laid out vertically. This makes it a better option for mobile devices because they have more space available vertically.

The responsive HTML5 text and image slider is incredibly user friendly. It has implemented drag-and-swipe-based navigation for desktop and mobile devices. It also lets you navigate through all the slides using a mouse wheel or with the left and right keyboard keys.

It offers a bunch of parameters to control the alignment and separation of different slides in both horizontal and vertical directions. There are three different skins, each of which can be used with three unique layouts to create a slider.

You can see how all the skins and parameters look and work in this live preview.

5. CSS3 Cube Slider

If you’re looking for a slider with a bit of a difference, check out the CSS3 Cube Slider. This slider shows off your images in a gorgeous slider like the other sliders here, but it does so with one of six cool 3D cube transition effects. 

The plugin works best in Chrome, Firefox, or Safari, but if the browser doesn’t support CSS3 then the slider falls back to the standard vertical or horizontal slide transition. The plugin is responsive and will adapt to any screen size for the user’s devices.

This is one of the best CSS sliders you will find!

6. Simple Image Slider Carousel

This simple image slider carousel actually comes with a lot of awesome layouts that you can use to showcase all your images. It's "simple" because it's easy to integrate into your own website.

It comes with quite a few important features. The responsive image slider with text layout has multiple display types to fit with all kinds of website designs. You can add lazy loading to the slider so that it only loads images when the user is about to scroll to the slider in the visible area.

You can create the image playlist using either HTML markup or JSON data. There are a lot of other features such as navigation based on swipe gestures and keyboard arrow keys. You can read about all of them on the product description page.

7. HTML5 Canvas Carousel

The HTML5 Canvas Carousel gives you another great option to display images on your website. This 3D photo gallery offers six different options for presenting your images. 

Features include touch-screen navigation support for mobile, support for PNG, JPEG, and GIF image files, ability to set the carousel position, and the possibility of featuring multiple carousels on the same page of your website. 

This responsive HTML5 carousel is highly customizable, and all options can be modified inside the XML file. It is optimized for both Android and iOS mobile devices, and the download file comes with a comprehensive help file explaining all configuration tags and installation.

8. Ultimate Media Gallery

The Ultimate Media Gallery is unique among the sliders in this list because it can display not just images but also video and audio files from a number of external content sources, including YouTube, Vimeo, Google Drive media, Podcast, and SoundCloud.  

This highly customizable gallery is fully responsive and mobile friendly. It takes full advantage of Font Awesome Library icons, and all demo examples are included in the download package for quick and easy setup.

9. HTML5 Canvas Cover Flow

The HTML5 Canvas Cover Flow slider is a 3D photo gallery that takes its inspiration from the Mac Finder viewer of the same name. The slider has tons of features and allows you to present your images in any way you want: horizontal, vertical, oblique, etc. Alternatively, you can make use of the predefined movements and styles if you prefer.

In addition, almost every aspect of the slider, including colors and graphic elements, can be customized to fit your site, and all the options can be easily modified from the configuration XML file, making maintaining the carousel much easier.

Optimized for mobile devices, it acts like a native app where you can touch, drag, and rotate the controls.

10. Shopping HTML5 Banners With Interactive Slider

These HTML5 banner sliders are meant to be used for creating HTML5 banner ad templates for AdWords, DoubleClick Studio, AdRoll and other ad platforms. This is the perfect plugin for people who want to create interactive ad banners to sell different products.

It is created with and fully editable in Google Web Designer. You can also change the colors and background with just a few clicks.

You can create ad banners in seven popular sizes: 160×600, 250×250, 336×280, 300×250, 728×90, 200×200, and 300×600. See them all in action in the live preview of the plugin.

The detailed documentation included with the plugin will provide a step-by-step guide to editing the template and creating your own interactive banner ads with sliders.

Free HTML5 Sliders for Images and Text

Some of the best HTML5 and CSS sliders are found on CodeCanyon. However, if you just want something simple, you can try out some of the free options first. Here are some of the most popular free HTML5 sliders for images and text.

bxSlider 4

This is a fully loaded, responsive slider built with jQuery. The slides can contain images, video, or other HTML content. You can get all the bxSlider 4 files from its GitHub page.

Swiper

Swiper is a free and modern responsive HTML5 slider which is designed as a mobile-based touch slider. It is usable on desktops as well. However, it does not implement keyboard- and mouse-based navigation.

Slick

Slick calls itself "the last carousel you'll ever need." It relies on jQuery and works in browsers as old as IE8. There are plenty of attributes to precisely control how the carousel behaves.

Tips for Using Sliders on Your Website

Here are a few tips to keep in mind to help you get the most value out of any slider carousels that you use on your website.

1. Use Sliders to Showcase Important Products and Services

Sliders and carousels will take up a large portion of the user's screen when they visit your website. This makes them ideal for pitching your best product or service. Also, make sure that you avoid clutter. Each slide in the carousel should focus on just one aspect of the product and do it well.

2. Include Call to Action Buttons

It is also important to include a direct call to action button somewhere on the carousel itself. If a visitor likes one of your products, they should not have to go somewhere else to make the purchase.

Other HTML5 Scripts and Templates

These ten best responsive HTML5 sliders are by no means the only ones available at CodeCanyon. You can find HTML5 widgets, scripts, and templates of every kind!

Categories: Web Design

Smashing Meets! Free Online Meetups On May 18th And 19th 2020

Smashing Magazine - Thu, 05/14/2020 - 06:00
Smashing Meets! Free Online Meetups On May 18th And 19th 2020 Smashing Meets! Free Online Meetups On May 18th And 19th 2020 Rachel Andrew 2020-05-14T13:00:00+00:00 2020-05-20T10:51:42+00:00

We’re having a meetup! Join us for Smashing Meets — two free online meetups with speakers, activities, and plenty of chances to make new friends. Just like a real meetup, though you’ll need to bring your own pizza.

What Will Happen At Smashing Meets?
  • 3×30-mins interactive talks from experts, followed by a short Q&A.
  • Interactive activities in breakout rooms, with friendly communities around the world and collaborative design and coding challenges.
  • A fun quiz show where you can win some smashing prizes!
Two Days, Different Timezones

To help make this a truly global meetup, we have two meets to sign up for:

We hope one of those will work for you, or come along to both! We will be happy to see you. More details on the speakers for each event below.

Smashing Meets: Day 1 (Monday, May 18th) MAY 18 Stage (Always open) Sessions Sessions 13:00 Doors open 13:10 Introduction by MC 13:25 Talk 1 with Yiying Lu: Creativity In Cross-Cultural Innovation Meet Designers & Coffee Toronto Design Challenge (by Mark Boulton and Vitaly Friedman) 13:55 Close & Introduction by MC 14:00 Talk 2 with Phil Hawksworth: Building With Jamstack — Keeping UIs And APIs Aligned Q&A Yiying Meet Woman of Design & Tech 14:30 Close & Introduction (by MC) 14:35 Talk 3 with Mark Boulton: Accessible Typography Emoji Challenge (by Yiying) Q&A Phil 15:05 Close & intro Quiz by MC 15:10 Super Smash Purrrty! by Charis and Peter Q&A Mark 15:40 Close close by MC
  • Building With JAMstack: Keeping UIs And APIs Aligned by Phil Hawksworth
    In his talk, Phil will shed light on some of the techniques you can use when working with serverless functions, proxies and Jamstack tools to help you build projects with confidence.
  • Accessible Typography by Mark Boulton
    Mark will be sharing his personal advice on how to use that particular typeface you want to use in the most accessible way. A practical talk that covers a bit of type design as well as the details of typesetting.
  • Creativity In Cross-Cultural Innovation by Yiying Lu
    Yiying will tell us how we can create more business and cultural value by integrating creativity in our product, messaging, and delivery. By the end of this talk, you’ll be sure to have learned how to start creating design that bridges the gap between Art and Tech, Business and Culture, East and West.
Smashing Meets: Day 2 (Tuesday, May 19th) MAY 19 Stage (Always open) Sessions Sessions 14:00 Doors open 14:10 Introduction by MC 14:25 Talk 1 with Mandy Michael: Fun With Browser And Sensor APIS Meet Talk.CSS Singapore Design Challenge (by Mark Boulton and Vitaly Friedman) 14:55 Close & Introduction by MC 15:00 Talk 2 with Rachel Andrew: Hello, Subgrid! Q&A Mandy Meet Web Weekend Kathmandu 15:30 Close & Introduction (by MC) 15:35 Talk 3 with Mark Boulton: Accessible Typography CodePen challenge (by HuiJing) Q&A Rachel 16:05 Close & intro Quiz by MC 16:10 Super Smash Purrrty! by Charis and Peter Q&A Mark 16:40 Close close by MC
  • Fun With Browser And Sensor APIs by Mandy Michael
    Whether it’s a practical implementation of the Light Sensor API or abducting a cat with a combination of sensors, Mandy will be looking — some simple code demos by exploring possibilities, tools and resources that are needed to create engaging and creative effects, visualizations and experiences.
  • Hello, Subgrid by Rachel Andrew
    In this talk, Rachel will introduce Subgrid alongside use cases, example code, and some thoughts on where we might see Grid heading in the future.
  • Accessible Typography by Mark Boulton
    Mark will be sharing his personal advice on how to use that particular typeface you want to use in the most accessible way. A practical talk that covers a bit of type design as well as the details of typesetting.

There are only a few days left to register, so sign up for the Meet (or Meets) of your choice here. It’s free, and we look forward to seeing you there.

(jn, il)
Categories: Web Design

Styling Components In React

Smashing Magazine - Thu, 05/14/2020 - 03:00
Styling Components In React Styling Components In React Shedrack Akintayo 2020-05-14T10:00:00+00:00 2020-05-20T10:51:42+00:00

Styling React components over the years has improved and become much easier with various techniques and strategies. In this tutorial, we’re going to learn how to style React components using four major styling strategies — with examples on how to use them. In the process, I will explain the cons and pros of these styling strategies, and by the end of this tutorial, you’ll know all about styling React components and how they work along with the various methods that can be used for styling these components.

Note: A basic understanding of ReactJS and CSS would be good to have for this tutorial.

What Does ‘Styling’ In React Applications Even Mean?

The reason you’ll style your React application is no different from that which you have in mind when styling other websites or web applications you have been working on. Styling in React applications describes how React components or elements are displayed on screen or any other media.

The whole essence of building frontend UIs with React is how flexible it is to build these UIs especially as components and also style them to give us a great look and experience. It is important to know that whatever styling strategy you may decide to use is still CSS — you are writing CSS like you’ve always done. The difference is that the strategies (which we’ll be looking at) help make the process easy because of the uniqueness of React.

Major Styling Strategies In React

There are various strategies to follow when planning to style React components, these strategies have also increased and evolved over the years. In this tutorial, we would be talking about the most popular and modern styling strategies, and how to use them to style our React components. These styling strategies include:

  1. CSS and SCSS Stylesheets
    This involves using separate stylesheets like our conventional way of styling our HTML websites either with CSS or a CSS preprocessor called SASS.
  2. CSS Modules
    A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.
  3. styled-components
    styled-components is a library for React and React Native that allows you to use component-level styles in your application that are written with a mixture of JavaScript and CSS using a technique called CSS-in-JS.
  4. JSS
    JSS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free and reusable way. It can compile in the browser, server-side or at build time in Node.

In the next section of this tutorial, we are going to be talking about each of these strategies of styling with examples of their syntax.

1. CSS And SASS Stylesheets

CSS or SCSS Stylesheets is a styling strategy that involves the use of external CSS or SASS stylesheets that can be imported into your React components depending on where you need the styling to be applied.

For example, we have a SASS file of styles called Box.scss we need to use in a component called Box.js, below is the code for our SASS file.

// Box.scss .Box { margin: 40px; border: 5px black; } .Box_content { font-size: 16px; text-align: center; }

In other to make use of this styling inside our Box component all we need to do is import the SASS file directly into our Box.js component like so:

import React from 'react'; import './Box.css'; const Box = () => ( <div className="Box"> <p className="Box_content"> Styling React Components </p> </div> ); export default Box;

After creating the styles and importing it into Box.js file, we can then set the className attribute to the match what we have in the stylesheet.

While using this strategy, you could also leverage on existing frameworks like; Bulma, Bootstrap, etc. These frameworks provide you with existing classes and components you could plug into your React application without styling every aspect of your application.

Benefits of using CSS and SASS Stylesheets
  1. It is much more popular than the rest of the styling strategies, so there is a ton of helpful resources when you run into a bug.
  2. Caching & Performance
    Standard CSS files are easy for the browser to optimize for, caching the files locally for repeat visits, and ultimately giving performance wins.
  3. Un-opinionated and Universal
    CSS and SASS is universal and has no opinion on how you render your UI making it a great choice for teams that have legacy CSS and are migrating over to a new framework or rebuilding their website or product.
  4. Quickly Iterate A New Design
    You can very easily rip out the entire stylesheet and create a new one to refresh the look and feel of your app without digging through potentially hundreds of components.
  5. CSS Frameworks
    CSS frameworks come in handy if you are a new developer, or you want to quickly work on a prototype without diving deep into writing your own full-blown stylesheets. CSS frameworks will provide you with building blocks to get your idea off the ground. Some of these frameworks include, Bootstrap, Bulma, Semantic UI, Materialize.
Shortcomings of using CSS and SASS Stylesheets
  1. Readability
    If not properly structured, a CSS or SASS stylesheet can become long and difficult to navigate through as the application becomes complex.
  2. Legacy CSS Can Live On For Years
    Most times these really large stylesheets can become so complex and long that cleaning up old, outdated or even unused styles can be a pain.
Note: “Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”) and is a superset of CSS syntax. This means that every valid CSS stylesheet is valid SCSS as well. SCSS files use the extension .scss.
The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.” CSS Modules

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. When using CSS Modules, each React component is provided with its own CSS file, that is scoped to that file and component alone.

The beauty of CSS modules happens at build time when the local class names which can be super simple without conflict are mapped directly to the automatically-generated ones and are exported as a JS object literal to use within React.

We can make use of CSS Modules in our React applications by importing the file directly into the component file.

For example, the code below is an example of how to use a CSS module in a React Component.

//Box.css :local(.container) { margin: 40px; border: 5px dashed pink; } :local(.content) { font-size: 15px; text-align: center; }

:local(.className) is used when you use create-react-app boilerplate because of webpack configurations.

When using webpack, you can add the loader and also include the module to your webpack.config.js in other to make CSS modules work with Webpack.

test: /\.css$/, loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' }

In other to make use of this CSS Module inside our Box component we need to import the module file directly into our Box.js component and use the className instead of style prop to access the style like so:

import React from 'react'; import styles from './Box.css'; const Box = () => ( <div className={styles.container}> <p className={styles.content}> Styling React Components </p> </div> ); export default Box;

styles here is an object that contains the styles we created in Box.css. This object will contain the classes; container and content that maps to their respective styles. To make use of them, we assign the element’s className to the appropriate class we have in Box.css.

Benefits Of Using CSS Modules
  1. Modular and reusable CSS,
  2. No more styling conflicts,
  3. Explicit dependencies,
  4. Local scope,
  5. Clear dependencies,
  6. No Code duplication in case of SSR,
  7. No Additional costs in JS payload,
  8. Variables, Sharing variables in CSS and exposing it to JavaScript.
Shortcomings of using CSS Modules
  1. Extra build tools (e.g. webpack).
  2. Mixing CSS Modules and global CSS classes is cumbersome.
  3. When a Reference is made to an undefined CSS Module, it resolves to undefined without a warning.
  4. Using the styles object whenever constructing a className is compulsory.
  5. Only allows usage of camelCase CSS class names.
styled-components

styled-components is a library for React and React Native that allows you to use component-level styles in your application that are written with a mixture of JavaScript and CSS.

It was created with the same method of operation of CSS Modules, a way to write CSS that’s scoped to a single component, and not accessible to any other element in the page or even component.

styled-components allows React developers to write plain CSS in React components without having to worry about clashing of class names.

For example, if we need to implement styling in our Box.js file using styled components, we would first need to carry out the following steps:

  • First, we need to install styled-components library by running npm install styled-components --save.
  • We then need to import the styled component library into our component by writing import styled from 'styled-components';.
  • Now we can create a variable by selecting a particular HTML element where we store our style keys.
  • Then we use the name of our variable we created as a wrapper around our JSX elements.

The code below is an implementation of all the steps we mentioned above.

import React from 'react'; import styled from 'styled-components'; const Box = styled.div` margin: 40px; border: 5px black; `; const Content = styled.p` font-size: 16px; text-align: center; `; const Box = () => ( <Box> <Content> Styling React Components </Content> </Box> ); export default Box;

In the code above, we import the styled object from styled-components, which makes use of tagged template literals to style your component. We then create a variable that would hold our styling and also act as a wrapper around content, that’s why we have the <Box> and <Content> tags, in this variables, we assign it to the styled object plus the HTML element we want to style then followed by the accompanying styles for the HTML element. To use the variables we created for styling all we need to do is wrap our JSX or content in between them as tags.

Benefits Of Using styled-components
  1. Consistency
    styled-components make it easy for you to publish a React component to NPM. These components can be customised through props and/or extending via styled(Component) and no clashing with CSS selectors.
  2. Sass Syntax Out-Of-The-Box
    You can get SASS trademark syntax out of the box without having to install or setup SASS or any extra build tool.
  3. Dynamic Styling
    You can make use of props to dynamically change the styles in any way that feels natural to anyone comfortable with React.
  4. Theming
    Using React’s Context API, styled-components offers a ThemeContext that can you can pass a theme object directly to, making it very accessible in any of your components, and by default can be interpolated into your styled definitions.
Shortcomings Of Using styled-components
  1. Learning Curve
    Frontend developers that are already comfortable with writing traditional CSS will have to learn a different way of styling that is different from how traditional CSS is written.
  2. Integration with Legacy CSS can be painful.
    If you’re making use of a UI library like Material UI or even traditional CSS, integrating styled-components together with them can be confusing to locate and debug styles.
  3. Performance
    styled-components converts all of the style definitions in your React component into plain CSS at build time and the inject everything into the <style> tags in the head of your index.html file. This affects performance in the sense that it is not only increasing the size of our HTML file which can have an impact on the load time, but there is also no way to chunk the output CSS either.
JSS

JSS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free and reusable way. It can compile in the browser, server-side or at build time in Node. JSS is a new styling strategy that hasn’t been adapted so much. It is framework agnostic and consists of multiple packages: the core, plugins, framework integrations and others.

JSS has third party API adapters that can be used to write JSS like styles but differently, these third party API adapters include:

  • Styled-JSS
    This is a styled-component API adapter.
  • Glamor-JSS
    Glamor flavored CSS with JSS under the hood.
  • Aphrodite-JSS
    Aphrodite like API.
React-JSS

React-JSS makes use of JSS with React using the new Hooks API. JSS and the default preset are already built into the library. According to the official React-JSS docs, the following are the benefits of using React-JSS instead of the core JSS library in your React components.

  • Dynamic Theming
    This allows context-based theme propagation and runtime updates.
  • Critical CSS Extraction
    The only CSS from rendered components gets extracted.
  • Lazy Evaluation
    Style Sheets are created when a component mounts and removed when it’s unmounted.
  • The static part of a Style Sheet will be shared between all elements.
  • Function values and rules are updated automatically with any data you pass to useStyles(data). You can pass props, state or anything from context for example.

The code below is an example of how React-JSS is used.

import React from 'react' import {render} from 'react-dom' import injectSheet, { ThemeProvider } from 'react-jss' const styles = (theme) => ({ wrapper: { padding: 40, background: theme.background, textAlign: 'center' }, title: { font: { size: 40, weight: 900, }, color: props => props.color }, link: { color: theme.color, '&:hover': { opacity: 0.5 } } }) const Comp = ({ classes }) => ( <div className={classes.wrapper}> <h1 className={classes.title}>Hello React-JSS!</h1> <a className={classes.link} href="http://cssinjs.org/react-jss" traget="_blank" > See docs </a> </div> ) const StyledComp = injectSheet(styles)(Comp) const theme = { background: '#aaa', color: '#24292e' } const App = () => ( <ThemeProvider theme={theme}> <StyledComp color="red"/> </ThemeProvider> ) render(<App />, document.getElementById("root"))

In the code above, which somewhat similar to using styled components, we import injectSheet and ThemeProvider from the react-jss library. The ThemeProvider is a High-Order component in React, which passes the theme object down the React tree by the use of context. It will contain the root theme of the component. While injectSheet is used for injecting the stylesheet we have created in this case styles into the main component.

const Comp = ({ classes }) => ( <div className={classes.wrapper}> <h1 className={classes.title}>Hello React-JSS!</h1> <a className={classes.link} href="http://cssinjs.org/react-jss" traget="_blank" > See docs </a> </div> )

The code above is the main React component that has not been injected with the styles object we have created, it contains the main code for our React component and it is going to be styled when we inject it with the styles object that we have created.

const StyledComp = injectSheet(styles)(Comp)

The line of code above is injecting the styles we have created into the component we created it for using the injectSheet() function.

const theme = { background: '#aaa', color: '#24292e' }

The code above holds the theme object that would be passed to the <ThemeProvider> HOC via context and it acts as the root theme of our component.

const App = () => ( <ThemeProvider theme={theme}> <StyledComp color="red"/> </ThemeProvider> )

In this portion of the code, what we are doing here is using the <ThemeProvider> HOC, we are rendering our component that we have injected the styled sheet we created into <StyledComp color= "red"/>.

At the end of rendering, this is what will be displayed on your bro.

Code Output. (Large preview) Benefits Of JSS
  1. Local Scoping
    JSS supports local scoping, taking it to the next level by automating scoping, which leads to a high level of predictability.
  2. Encapsulation
    Encapsulation facilitates maintenance and eliminates errors, as you can modify all component-related code and style in the same place, without having to worry about unexpectedly changing other parts of the application.
  3. Reusability
    Components are reusable, so you only have to write them once, then you can run them everywhere while maintaining their styling too.
  4. Dynamic Styling
    You can make use of props to dynamically change the styles in any way that feels natural to anyone comfortable with React.
Shortcomings Of JSS
  1. Learning Curve
    Learning JSS can be very tricky especially frontend developers that are already used to writing traditional CSS.
  2. Extra Layer of Complexity
    Putting a CSS-in-JS library into use adds an extra layer to your React application, which can sometimes be unnecessary.
  3. Code Readability
    Custom or Automatically generated selectors can be very difficult to read especially when using your browser devtools to debug.
Conclusion

Each of these has its advantages and disadvantages, and it all depends on your personal/company preference and the complexity of your application. Also, whatever styling strategy you may decide to use, it is still basically CSS. You can write CSS like you’ve always done, but React and other libraries offer solutions that can also help with styling.

I hope you enjoyed working through this tutorial. You could always read more on Styling React Components from the references below. If you have any questions, leave a comment below and I’ll be happy to reply to each and every single one.

Resources (ks, ra, yk, il)
Categories: Web Design

16 Best Tab and Accordion Widget Plugins for WordPress

Tuts+ Code - Web Development - Wed, 05/13/2020 - 08:35

Your website's content should be organized and beautiful. By adding a tab or accordion widget plugin to your WordPress website, you will be able to display your website's content in an elegant way. 

An interactive accordion and tab plugin can tidy up the design and readability of your webpages. 

One of the many fully customizable WordPress tab & accordion plugins and widgets on CodeCanyon

Accordions and tabs are great ways to communicate text-heavy information in a stylish and condensed way. Keeping your website clutter-free and interactive should be the main priority for your website, and accordions and tabs help you accomplish this. 

At CodeCanyon, you will be able to choose from a library of premium plugins available and find a tab and accordion plugin and widget that will fit your website's theme and allow you to display your website's information without crowding your page's designs. 

The Best WordPress Tab and Accordion Plugins on CodeCanyon

Discover CodeCanyon's extensive library of the best tab and accordion WordPress widgets and plugins ever created. With a cheap one-time payment, you can purchase these high-quality WordPress widgets and plugins and draw in more traffic to your website. 

Here are a few of the best-selling tab and accordion WordPress widgets available on CodeCanyon for 2020.

Best-selling tab and accordion widgets and plugins available on CodeCanyon 

These powerful tab and accordion plugins allow you to display your website's text and media in a systematic order that fits your particular website. These widgets and plugins come with plenty of features that can enhance your website, including:

  • pagination
  • animated layers
  • customizable columns and rows
  • touch-enabled mobile functionality 
  • lightboxes

Head on over to CodeCanyon and choose from the premium tab and accordion plugins available now! 

11 Best Tab and Accordion WordPress Widgets for 2020

Here are 11 of the top-rated WordPress tab and accordion widgets and plugins that are available for you to download on CodeCanyon:

1. Accordion Slider—Responsive WordPress Plugin

The Accordion Slider plugin combines two great functions in one handy plugin. First it functions as an accordion, and secondly it functions as a slider.

Best features:

  • add as many panels as you want, without worrying about screen space
  • touch-enabled to work well with mobile screens  
  • loads images and content from posts, galleries, and Flickr
  • accordions are automatically cached to improve the load time
  • can be placed anywhere: in posts/pages, template PHP code, or widgets

Accordion Slider—Responsive WordPress Plugin is a great two-in-one plugin that will appeal to those looking for a great way to present images or text.

2. Grid Accordion—Responsive WordPress Plugin

One of the best-looking accordions out there, Grid Accordion adds a fresh feel to your site by offering a feature not found in other plugins: an accordion that works in two directions. While most plugins let you open and close tabs or similar UI elements either horizontally or vertically, with this plugin, you can do both. Not only does it handle text content well within its accordion grid, but you can even fill your content areas with images and other media for a more stunning effect.

Make sure to check out the demo for Grid Accordion here.

This plugin also comes with a host of other features, such as:

  • a fully responsive and touch-enabled design
  • support for dynamic content from posts and galleries
  • available hooks for actions and filters
  • JavaScript API endpoints for maximum customization
3. WP Responsive FAQ With Category

The WP Responsive FAQ With Category plugin is specifically designed for users who have or want to add a Frequently Asked Questions area to their site and don’t want their visitors to have to scroll through an endless stream of text to get to the questions and answers that are relevant to them.

Best features:

  • FAQs can be arranged by category
  • 15 customizable different designs to choose from
  • compatible with Visual Composer page builder and WooCommerce
  • two types of FAQ toggle icons: arrow or plus sign

There’s no question that WP Responsive FAQ with Category is the answer to all your FAQ needs.

4. WooCommerce Category Accordion

The WooCommerce Category Accordion is designed specifically for WooCommerce users. It can be used as a widget or shortcode to list product categories and subcategories.

Best features:

  • supports unlimited categories and subcategories
  • 14 Font Awesome icons included
  • ability to highlight current category option
  • sort by ascending or descending order

WooCommerce Category Accordion is ideal for users who want to organize their products or services into categories and subcategories to make it easier for customers to navigate their site.

5. Responsive Searchable 3 Level Accordion

Responsive Searchable 3 Level Accordion is a simple plugin that can be used anywhere on your WordPress site. It will appeal to users who are looking to arrange content in accordion style within a post, sidebar, footer, etc.

Best features:

  • can be used as a widget or shortcode
  • three nesting levels available
  • five ready-made styling options
  • allows users to type in searched phrase

Responsive Searchable 3 Level Accordion For WordPress is a low-fuss plugin, and its standout features like three-level support and searchable content really set it apart.

6. Accordion FAQ WordPress Plugin

FAQ pages are an important part of almost any website, and with this plugin, you can fit a mountain of text behind a sleek and easily digestible display. This accordion plugin focuses on doing one thing, creating FAQ-style content easily, and it does it well.

Here’s what you can expect to get with this plugin:

  • ability to quickly add multiple FAQ accordions throughout your site
  • easy drag-and-drop interface for reordering
  • color, icon, and font customization
  • built-in generator for creating shortcodes

If you’re looking to add an FAQ section to your existing design, then the Accordion FAQ WordPress Plugin has you covered.

7. WordPress Tabs and Accordions DZS

WordPress Tabs and Accordions DZS is another plugin that gives users access to both tab and accordion functions.

Best features:

  • full skins to fit every brand
  • WYSIWYG editor
  • unlimited color options for customization
  • iPhone, iPad, and Android optimized
  • and more

So if StackTabs doesn’t appeal, WordPress Tabs and Accordions DZS is another great two-for-one option.

8. Side Tabs—Layered Popups Add-on

A little different than most of the plugins on this list, Side Tabs delivers the features you’d expect from a tab plugin, but instead of existing within your site’s content, they live at the edge of your screen. This unique presentation creates a number of unusual uses.

One of the most interesting ways you can use Side Tabs is to present a constant access point to content throughout an entire page (or several pages). Besides that, it also makes a great tool for offering Calls to Action and similar content without being too intrusive.

With a ton of customization and animation options available out of the box, this plugin works brilliantly for anyone looking to add a fresh way of presenting information to their site.

9. WooCommerce Tabs Pro: Extra Tabs for Product Page

If you have a WooCommerce site, the WooCommerce Tab Pro plugin will allow you to create and manage 11 different types of tabs to display your products.

Best features:

  • ability to add unlimited tabs to a single product page
  • WYSIWYG editor for editing custom content
  • ability to enable or disable tabs
  • ability to create a global tab that can be used with all products

When you have an eCommerce site, making improvements to your layout can really boost sales. With WooCommerce Tabs Pro: Extra Tabs for Product Page, the tills will soon be ringing.

10. Elegant Tabs for Visual Composer

Elegant Tabs for Visual Composer is an add-on for the WPBakery WordPress plugin (formerly Visual Composer). It lets you add any shortcode to multiple tabs and offers loads of customization like different colors, icons, and backgrounds for different sections or tabs.

Best features:

  • vertical tabs
  • drag and drop any WPBakery elements inside the tab content
  • supports deep linking
  • ten different styles of tabs and unlimited variations
  • and more

Elegant Tabs is also available for Fusion BuilderWooCommerceCornerstone, and Beaver Builder.

11. PullOut Widgets for WordPress

Like the Social Network Tabs for WordPress, the PullOut Widgets is a different take on tabs. It is specifically designed to turn any widget on your site into a pullout tab.

Best features:

  • 289 icons for pullout tabs
  • 32 sliding animation effects
  • unlimited pullout widget positioning on the top, right, bottom, or left side
  • unlimited widget colors

The most successful websites are interactive, and PullOut Widgets for WordPress gives your visitors plenty of chances to engage with your content.

5 Free Tab and Accordion WordPress Widgets and Plugins for Download in 2020

The best features and most beautiful interfaces are found in the premium plugins from CodeCanyon. But, if you're on a budget or just want something simple, check out these free tab and accordion plugins for WordPress.

1. Arconix Shortcodes

Arconix Shortcodes is a very versatile plugin and is a must-have if you cannot afford any of the premium plugins. With this plugin, you can add not only accordions but styled boxes, buttons, tabs, unordered lists, columns, and much more.

2. Easy Accordion

Easy Accordion is a responsive drag-and-drop accordion builder that will help you to display multiple accordions on your WordPress website. No coding is necessary to add the accordions to your website as everything is added through shortcodes.

3. Accordion

This Accordion plugin can help you create different sections of your website, including but not limited to FAQs, a knowledge base, and a question & answer section. You can change colors, font size, and icons for each accordion.

4. Squelch Tabs and Accordions Shortcodes

With the use of shortcodes, you can add horizontal accordions, vertical accordions, and tabs. This free plugin will help you save space on your webpages, make your website look more professional, and add an interactive component to your website.

5. Shortcodes Ultimate

Shortcodes Ultimate allows you to add many tools to your website. You can easily create tabs, buttons, boxes, sliders and carousels, and responsive videos. The plugin comes with over 50 shortcodes for you to implement. 

How to Add an FAQ Accordion to Your Website

In this example, we are going to create an FAQ section for our online store. 

First, we need to create a category for our FAQ accordion so the plugin knows what content to add to each specific accordion. Once you have installed the Accordion FAQ WordPress plugin, head on over to WP Dashboard > FAQ > Categories. In the name field, we will type "Online Store" and click the Add New Category button. 

Next, we will click on WP Dashboard > FAQ > Add New. We will add our three FAQ entries this way. We will include the question in the title and the answer in the text editor. 

For each of our entries, we will make sure to click the checkbox next to the category, Online Store, that we created to make sure we group the entries together. 

Once we have added our three FAQ entries for our online store, it is time to add the accordion widget to a page. On an existing or new page or post, click on the Add Shortcode button on the top of the text editor. Choose Insert FAQs from the Select a Shortcode drop-down menu. From here we will be given a basic group of settings for us to change. We will choose the Online Store category from the Faq Category option and change the Icon Background Color to blue. 

Click the Insert Shortcode button, and the shortcode will be added to the text editor. The FAQ accordion will now be displayed on your webpage for all your users to see!

Install a Tab or Accordion WordPress Widget Now! 

By adding a premium tab or accordion plugin to your website, you will be able to simplify your web page's design and display your text and media in an easy-to-understand way. 

These handy widgets and plugins allow you to integrate interactive displays for your website's content that can be styled to fit your website's theme. 

In addition to all the high-quality tab and accordion widgets available, there are also thousands of other high-quality WordPress plugins on CodeCanyon that can help enhance your website. Take look through this massive collection of plugins and you will find all types of plugins, including gallery, newsletter, eCommerce, and marketing plugins.

Categories: Web Design

How To Convince Others Not To Use Dark Patterns

Smashing Magazine - Wed, 05/13/2020 - 05:00
How To Convince Others Not To Use Dark Patterns How To Convince Others Not To Use Dark Patterns Paul Boag 2020-05-13T12:00:00+00:00 2020-05-20T10:51:42+00:00

You are a smart, well-informed person. After all, you are reading Smashing Magazine so you must be. That means you are probably already convinced that you should avoid dark patterns. Maybe you have even read the Ethical Design Handbook that drives the point home.

However, just because we understand that we should avoid dark patterns, doesn’t mean our clients and colleagues do. No doubt you have been asked more than once to implement these questionable techniques by an ill-informed stakeholder.

Unfortunately, it can be hard to convince them that dark patterns are a terrible idea. Talking about ethics often isn’t enough.

The problem is that a lot of our colleagues and clients are under tremendous pressure to deliver. Business owners need to pay the bills, while many marketing executives in larger organizations are under immense pressure to deliver results.

In that kind of environment, people can convince themselves of anything. The ethical argument becomes muddied as people persuade themselves that they aren’t forcing anybody to do anything.

So in this post, we will put together a compelling argument you can present to stakeholders to help them understand why dark patterns are a bad idea.

However, before we do that, let’s agree on a definition of dark patterns.

How do we encourage clicks without shady tricks? Meet Click, our new practical handbook on how to increase conversion and drive sales without alienating people along the way. By Paul Boag. May 2020.

Jump to the details ↬ How Do We Define A Dark Pattern

Suzanne Scacca has written an excellent post showing examples of dark patterns and you probably already have a clear idea in your mind of what they are.

However, for this article, I am going use the definition from my article on dark patterns:

“User interface elements that have been carefully crafted to trick users into doing things they might not otherwise do, often utilizing psychological manipulation.”

We need to be clear on our definition because increasingly, I am seeing people refer to anything that is annoying on the web as a dark pattern. For example, an overlay may be very annoying, but it does not necessarily trick users into doing something they might not otherwise do.

This page is designed to trick people into adding insurance to their order by making the button green and having it point onwards. (Large preview)

I point this out, not to say those people are wrong in their definition, but rather because the arguments I lay out here would not all apply to a broader definition of what a dark pattern is.

So what exactly is that argument?

The Business Case Against Dark Patterns

If you want to convince stakeholders that dark patterns are a terrible idea, there is little point talking about their negative impact on the user experience. That is typically too abstract for most people. Instead, we need to frame things in terms they will understand — the negative impact of dark patterns for them personally and for the entire business.

Aside from the ethical considerations of using dark patterns, three factors make them a wrong choice for any business concerned about long-term revenue, and by extension, anybody in that business considering adopting them. These are:

  • The fact that consumers are cynical, savvy and spoilt for choice.
  • That the web has empowered consumers.
  • The hidden costs of dark patterns.

These are the arguments that you can bring to clients and management so let’s explore them in more depth.

Consumers Are Cynical, Savvy And Spoilt For Choice

You only need to watch an episode of Mad Men to know that manipulation in sales and marketing has been around much longer than the web.

Brands always used to be able to get away with manipulation because consumers were mostly unaware of being manipulated. Even if they did realize, the choice was limited, and so there was very little they could do. That is no longer true. The web has changed that.

We need to help management realize the fact that consumers have changed. That in every consumer’s pocket is instant access to every other company on the planet that offers the same thing as you. It is so easy to find your competitors and so simple to swap that one small annoyance is enough to make people switch.

Of course, management might take the cynical attitude that if people are unaware that they are manipulating them, then they won’t be annoyed and so won’t swap to a competitor.

In truth, the assumption that people are unaware of manipulation is incorrect.

There is a tendency to think that because dark patterns work (and let’s be clear they do) that people are unaware of them. However, that isn’t necessarily so.

A case in point is a usability test I ran on a hotel booking site which employed dark patterns. As the user was looking at hotel rooms, he commented on how he hated all the manipulative techniques the website used. I asked him why he used the site, and he said: “I just ignore all of that stuff.”

In reality, he probably didn’t. It would still impact his buying decision on a sub-conscious level. Yes, he was unaware the manipulation was working. However, he was aware the site was employing it, and so it created that adverse reaction in him.

Users are much savvier than we give them credit for. Don’t forget they have the whole of human knowledge in their pockets, and they read articles about Facebook’s psychological manipulations or BBC stories about Government intervention over the techniques hotel booking sites were employing. They know that websites are attempting to manipulate them, and that makes it likely they will at least consider going elsewhere.

The media is ensuring that consumers are increasingly aware of dark patterns. (Large preview)

However, there is an even more significant danger in them knowing that a site is attempting to manipulate them.

The Power Of The Consumer

The web hasn’t just made consumers savvier and given them more access to choice. It has also provided them with a platform to complain, and companies continue to underestimate that.

Even one disgruntled customer can have a significant negative impact on a brand. I often talk to clients about the story of Hasan Syed, who was unhappy with British Airways. He decided to take out a promoted tweet that read:

“Don’t fly @BritishAirways. Their customer service is horrendous.”

The fallout of this one action was enormous for British Airways with the story featuring on the BBC, Guardian, Fox News, the Express and Telegraph, to name just a few.

One disgruntled company can undermine a brand. (Large preview)

Things get even more dangerous when users start coming together to express their dissatisfaction, such as when Facebook was found to have carried out psychological experiments on their users.

The voice of users has become so powerful now that it motivates government into action such as with the Competition and Markets Authority (CMA) here in the UK. They recently announced:

“The CMA has taken enforcement action to bring to an end misleading sales tactics, hidden charges and other practices in the online hotel booking market. These have been wholly unacceptable.”

Worst of all, the web means these negative comments from users never go away. They are always only a search away and easily accessible thanks to sites like Check a Trade or Trip Advisor.

Sites like Trustpilot provide a platform for consumers to express their feelings about an online experience. (Large preview)

In business terms, this leads to lost long-term revenue, less repeat orders, and harder customer acquisition. However, these are not the only costs of manipulation.

The Hidden Cost Of Manipulation

At face value, dark patterns work. If you use them on your website, you will see an increase in users taking action. However, that does not tell the whole story because for every dollar of additional revenue earned; dark patterns could well be costing you more. The problem is that you cannot easily see the costs.

Take, for example, a company I worked with who sold kettles. They decided to automatically add their kettle filters to people’s carts when they went to buy a kettle. That is a classic dark pattern people don’t always notice that the company has added the filter.

Sure enough, the sales of filters skyrocketed, and the e-commerce team was pleased because they were one step closer to meeting their targets.

Unfortunately what they were not aware of was what was happening elsewhere in the company.

The marketing team who ran the companies social media channels found themselves having to spend time addressing complaints on Twitter and Facebook.

The customer support team received an increase in calls asking for refunds or complaining. Each call was costing the company £3.21, more than the profit margin on the filters.

Then there was the cost of processing the returns. Filters had to be assessed and then restocked, costing yet more money.

In short, dark patterns are rarely as profitable as they first appear and could be costing the company money, even outside of the online backlash.

Without a doubt, there is a solid business case against the use of dark patterns. However, an academic argument may not be enough to sway clients or colleagues. You might need something more tangible.

Gather Your Evidence

If your company has yet to start using dark patterns, the above argument should help. However, if they are already using them, getting people to change their minds will be tougher. You will probably need some evidence to support your case.

Gathering this evidence will need a bit of detective work on your part, but it could make all of the difference in making your case. With that in mind, where are some places to look?

Search Out Negative Comments

The first place to look is online. Search out every negative comment you can find about dark patterns and your website. If you don’t see any that doesn’t mean people are unhappy, it just means they haven’t shared it publicly yet. However, if you do find comments, they probably represent the feelings of many, many other people.

A simple search on social media will uncover lots of examples of people annoyed by dark patterns. (Large preview) Talk To Other Teams In Your Company

Speak to those in customer services, returns, marketing or any other department that might have been impacted by the use of dark patterns. Ask them if they have noticed any changes since the company has implemented them. As with the kettle company, you might find some hidden costs.

Run Usability Testing

Ask some people to use your site and see how they react to the dark patterns. I would advise against leading the testers by asking directly about the dark patterns. However, you can ask whether there is anything about the website they dislike or find annoying.

Make sure you record these sessions too, as nothing is more potent than seeing just how frustrated and irritated people get with these kinds of techniques.

Run A Survey

Another approach is to run a survey asking people about their impressions of the website. Did they find it trustworthy? Do they feel the company is putting their interests first?

One particular survey I favor is one that shows on exit-intent if the user decides not to take action. The one question survey asks them why they chose not to take action and offers them a list of alternatives.

A simple survey can help assertion how dark patterns are influencing people’s attitude towards your website. (Large preview)

One of the options could be that the site felt manipulative or untrustworthy. That would give you an indication of if users are aware of the dark patterns and whether they are influencing the buying decision negatively.

That works even better if you can compare answers between users who have seen the dark patterns and those who haven’t.

Of course, the best evidence of all is where you can tie dark patterns to financial loss for the company. That is not always easy to do, but with some educated guessing, we can often estimate.

Let’s imagine one in ten people who completed the exit-intent survey said that they didn’t act because the site felt manipulative. That would mean that by dropping dark patterns, the site could see 10% more people taking action. If you know the number of visitors to the website, you can work out how many extra orders that would be. You can then also work out the average value of each order, and that provides a financial cost of dark patterns.

Would that number be 100% accurate? Absolutely not. However, it would be enough to make stakeholders stop and think. At least it will if you present it in the right way.

Pick Your Moment And Method

In my experience, one of the significant reasons that our appeals to drop dark patterns fall on deaf ears is that we approach it in a confrontational manner. We argue passionately for the removal of dark patterns in a meeting, often with the person who introduced them in the first place. That is never going to end well.

When we confront people in this way, they become defensive, especially when you are criticizing them in front of colleagues.

My recommendation is that once you have formed your argument and gathered your evidence that you speak to each of the critical stakeholders individually.

Not only does this approach avoid people feeling attacked in a public forum, but it also allows you to tailor the argument you present for whoever you are talking to.

For example, if you are talking to a marketing person, you could talk about the damage dark patterns have on a brand. However, if you are talking to a finance person, you can discuss the hidden costs of dark patterns.

Most of all, we need to make these arguments with sensitivity. We should not imply that stakeholders were wrong to suggest or try dark patterns. That is simply too confrontational.

You will see better results if you talk about the evidence that you have uncovered and the research into the subject that you have done online. Talk about it being a nuanced issue and a delicate balance to achieve. In short, be conciliatory, rather than confrontational.

I am not claiming that if you adopt the approach outlined in this article, you will see success every time. However, I do believe you will see more progress than lecturing colleagues about ethics and applying that they are unethical in their approach.

(ra, il)
Categories: Web Design

Meet “Click!”: Encourage Clicks Without Shady Tricks

Smashing Magazine - Tue, 05/12/2020 - 04:00
Meet “Click!”: Encourage Clicks Without Shady Tricks Meet “Click!”: Encourage Clicks Without Shady Tricks Vitaly Friedman 2020-05-12T11:00:00+00:00 2020-05-20T10:51:42+00:00

The web has become a noisy place with millions of companies trying to get users’ attention. No wonder many of them apply increasingly desperate techniques to encourage users to act on their websites. We’ve seen an explosion of dark patterns attempting to manipulate users into handing over personal data or make a purchase.

However, these manipulative techniques come with hidden costs in customer service, maintenance, support, return processing fees, and social media backlash. They cost a fortune and hurt business irrevocably.

How, then, do we encourage users to act? How do we increase clicks without shady techniques? By establishing trust with small commitments, at the right time, and in the right order. Click! explains how to do just that. Jump to table of contents and download a free PDF excerpt (1 MB).

Print + eBook { "sku": "click", "type": "Book", "price": "39.00", "sales_price": "29.00", "prices": [{ "amount": "39.00", "currency": "USD", "items": [ {"amount": "29.00", "type": "Book"}, {"amount": "10.00", "type": "E-Book"} ] }, { "amount": "39.00", "currency": "EUR", "items": [ {"amount": "29.00", "type": "Book"}, {"amount": "10.00", "type": "E-Book"} ] }, { "amount": "29.00", "currency": "USD", "items": [ {"amount": "21.00", "type": "Book"}, {"amount": "8.00", "type": "E-Book"} ] }, { "amount": "29.00", "currency": "EUR", "items": [ {"amount": "21.00", "type": "Book"}, {"amount": "8.00", "type": "E-Book"} ] } ] } $ 29.00 $ 39.00 Get Print + eBook

Quality hardcover. Free worldwide shipping, starting early June. 100 days money-back-guarantee.

eBook { "sku": "click", "type": "E-Book", "price": "19.00", "sales_price": "14.90", "prices": [{ "amount": "19.00", "currency": "USD" }, { "amount": "19.00", "currency": "EUR" }, { "amount": "14.90", "currency": "USD" }, { "amount": "14.90", "currency": "EUR" } ] } $ 14.90 $ 19.00 Free! Get the eBook

DRM-free, of course. ePUB, Kindle, PDF.
Included with Smashing Membership.

Get the eBook

Download PDF, ePUB, Kindle.
Thanks for being smashing! ❤️

About The Book

There is no shortage in books on marketing and user experience. But when it comes to bridging the gap between the two, many of us struggle to find the right balance. As businesses, we need to meet out targets — be it with install app prompts, newsletter overlays or infamous chat widgets. But as designers, we don't want to end up with a frustrating user experience. We really need both, and we need a strategy to get there.

That's why we've written Click! — a guide with practical strategies for improving conversion and retention while building user's loyalty and trust. The book explores how to effectively address user concerns, overcome scepticism and encourage users to act — helping you meet your business targets and KPIs along the way. Whether you are a designer, marketer, entrepreneur or product owner, this book will surely help you avoid hidden costs and drive sales.

Here's a short video message from Paul Boag, the author of Click!, explaining why he's written the book and what it's all about:

By reading this book, you will learn to:

  • Measure and boost business KPIs effectively,
  • Build a user-centric sales funnel,
  • Reduce risks and address objections,
  • Build trust and overcome skepticism,
  • Persuade people without alienating them,
  • Establish a strategy for higher conversion.
  • Psst! A little surprise shipped with the first 500 books.
  • Download a free PDF sample (23.7 MB) and get the book right away.
The book features interface design examples that take ethical design principles into the account. Large preview. The cover and chapter illustrations carefully designed by Veerle Pieters. (Large preview) Table Of Contents

The book is split into 11 chapters. We'll start by exploring the psychology of decision making and how to measure conversion. Then we'll build a user-centric sales funnel and address user concerns effectively. Finally, we'll explore how to encourage users to act without alienating them.

“This is a great book on how to practically, and ethically, optimise website conversion rates. Before, I was roughly aware of what CRO was, but now I feel confident to start implementing these techniques in projects. As you would expect, Paul explains all of the concepts in an easy-to-follow and friendly manner.”

— Dave Smyth, Agency Owner “I picked up a super simple testing idea, and saw a 42% lift in conversion rate. It was surprising to me, so I ran it again to significance with the same result. That equates to about 2.5 million USD/year in revenue at no additional cost. So I’d say I got my money’s worth!”

— Brandon Austin Kinney, Director of Lead Generation

368 pages. The eBook is already available (PDF, ePUB, Amazon Kindle). We’ll ship printed copies early June 2020. For designers, marketers, entrepreneurs and product owners. Written by Paul Boag. Designed by Veerle Pieters.

Print + eBook { "sku": "click", "type": "Book", "price": "39.00", "sales_price": "29.00", "prices": [{ "amount": "39.00", "currency": "USD", "items": [ {"amount": "29.00", "type": "Book"}, {"amount": "10.00", "type": "E-Book"} ] }, { "amount": "39.00", "currency": "EUR", "items": [ {"amount": "29.00", "type": "Book"}, {"amount": "10.00", "type": "E-Book"} ] }, { "amount": "29.00", "currency": "USD", "items": [ {"amount": "21.00", "type": "Book"}, {"amount": "8.00", "type": "E-Book"} ] }, { "amount": "29.00", "currency": "EUR", "items": [ {"amount": "21.00", "type": "Book"}, {"amount": "8.00", "type": "E-Book"} ] } ] } $ 29.00 $ 39.00 Get Print + eBook

Quality hardcover. Free worldwide shipping, starting early June. 100 days money-back-guarantee.

eBook { "sku": "click", "type": "E-Book", "price": "19.00", "sales_price": "14.90", "prices": [{ "amount": "19.00", "currency": "USD" }, { "amount": "19.00", "currency": "EUR" }, { "amount": "14.90", "currency": "USD" }, { "amount": "14.90", "currency": "EUR" } ] } $ 14.90 $ 19.00 Free! Get the eBook

DRM-free, of course. ePUB, Kindle, PDF.
Included with Smashing Membership.

Get the eBook

Download PDF, ePUB, Kindle.
Thanks for being smashing! ❤️

About The Author

Paul is a leader in conversion rate optimisation and user experience design thinking. He has over 25 years experience working with clients such as Doctors Without Borders and PUMA. He is the author of six books and a well respected presenter.

--> About the Author

Paul Boag is a leader in conversion rate optimisation and user experience design thinking. He has over 25 years experience working with clients such as Doctors Without Borders and PUMA. He is the author of six books and a well respected presenter.

Technical Details Community Matters ❤️

With Click!, we’ve tried to create a very focused handbook with pragmatic solutions to help everyone create a better digital product that doesn't get abandoned due to sheer number of pop-ups, install prompt and newsletter box overlays.

There is quite a bit of work to do on the web, but our hope is that with this book, you will be equipped with enough techniques to increase conversion and the number of happy customers.

Producing a book takes quite a bit of time, and we couldn’t pull it off without the support of our wonderful community. A huge shout-out to Smashing Members for their ongoing support in our adventures. As a result, the eBook is and always will be free for Smashing Members. Plus, Members get a friendly discount when purchasing their printed copy.

Stay smashing, and thank you for your ongoing support, everyone!

Print + eBook { "sku": "click", "type": "Book", "price": "39.00", "sales_price": "29.00", "prices": [{ "amount": "39.00", "currency": "USD", "items": [ {"amount": "29.00", "type": "Book"}, {"amount": "10.00", "type": "E-Book"} ] }, { "amount": "39.00", "currency": "EUR", "items": [ {"amount": "29.00", "type": "Book"}, {"amount": "10.00", "type": "E-Book"} ] }, { "amount": "29.00", "currency": "USD", "items": [ {"amount": "21.00", "type": "Book"}, {"amount": "8.00", "type": "E-Book"} ] }, { "amount": "29.00", "currency": "EUR", "items": [ {"amount": "21.00", "type": "Book"}, {"amount": "8.00", "type": "E-Book"} ] } ] } $ 29.00 $ 39.00 Get Print + eBook

Quality hardcover. Free worldwide shipping, starting early June. 100 days money-back-guarantee.

eBook { "sku": "click", "type": "E-Book", "price": "19.00", "sales_price": "14.90", "prices": [{ "amount": "19.00", "currency": "USD" }, { "amount": "19.00", "currency": "EUR" }, { "amount": "14.90", "currency": "USD" }, { "amount": "14.90", "currency": "EUR" } ] } $ 14.90 $ 19.00 Free! Get the eBook

DRM-free, of course. ePUB, Kindle, PDF.
Included with Smashing Membership.

Get the eBook

Download PDF, ePUB, Kindle.
Thanks for being smashing! ❤️

More Smashing Books

Promoting best practices and providing you with practical tips to master your daily coding and design challenges has always been (and will be) at the core of everything we do at Smashing.

In the past few years, we were very lucky to have worked together with some talented, caring people from the web community to publish their wealth of experience as printed books that stand the test of time. Trine, Alla and Adam are some of these people. Have you checked out their books already?

Ethical Design Handbook

Add to cart $39

Design Systems

Add to cart $39

Form Design Patterns

Add to cart $39

Categories: Web Design

Micro-Typography: How To Space And Kern Punctuation Marks And Other Symbols

Smashing Magazine - Tue, 05/12/2020 - 03:30
Micro-Typography: How To Space And Kern Punctuation Marks And Other Symbols Micro-Typography: How To Space And Kern Punctuation Marks And Other Symbols Thomas Bohm 2020-05-12T10:30:00+00:00 2020-05-20T10:51:42+00:00

This article is for anyone who works with typography, in any medium, and it is especially for those designers who are keen to give users the best reading experience possible.

Jeffrey Zeldman once said:

“90% of design is typography. And the other 90% is whitespace.”

You might be knowledgeable about typefaces; you might regularly modify the leading, tracking, and kerning of your fonts; you might optimize the file sizes of your web fonts — but is that all that can be done? For hundreds of years, typographers and typeface designers have been using white space in typography. In this article, I will discuss the spacing and kerning of punctuation marks and other symbols, looking at what people say about the effects of these adjustments. I will show you different ways to go about doing this work, the pitfalls, and how we might do it more accurately, quickly, and consistently.

This article will show you how to analyze typography in more detail, and how to better judge spacing and micro-typographic details, especially in typefaces designed for extended reading. You will learn a lot about how typefaces are built and given to you in its default state.

Typographers have a long history of not accepting what they are initially given, in order to achieve optimum performance for readers. There are also accessibility benefits from properly spacing punctuation marks and other symbols for different types of people (such as aging readers and children around six years old). This article will advance your typographic skills, help you produce a better reading experience, improve your typesetting skills, and enable you to deliver effortless reading of a large volume of text on web pages or in code framework/API documentation.

What Spacing Are We Referring To?

Below is a simple example of what spacing looks, not applied and applied:

Figure 1: This example is from Jost Hochuli’s book Detail in Typography. Set in Minion Pro Regular (version 2.068). No tracking applied; justification: desired, 100%. (Large preview)

You might not be able to see much difference, but there is. Welcome to micro-typography. This article is somewhat of a how-to about the issues and problems. We’ll need to explore the issues both in print (how it has been done in the past) and on the web (how it can be done in the present). The past informs the present.

There are also other benefits to spacing punctuation marks and other symbols (though currently untested, with little evidence available). Have you considered people with vision impairments; the extra space given could be beneficial and add clarity, because the marks would not so squished against the next character. What about children around 6 years old, who are learning to read. Does the extra white space, and thus extra time and emphasis, lead to more awareness of these marks?

Why Space Punctuation Marks And Other Symbols?

You may remember letterpress typesetting or have done it yourself. There, a vast range of space characters are used, as Marcin Wichary points out. The subject of spacing punctuation marks and other symbols in typography and typesetting has held my attention for some time. In high-end typographic design books and manuals by experts (for example, Detail in Typography by Jost Hochuli), it is widely regarded that spacing punctuation marks and miscellaneous symbols should be done and is good to do. This is somewhat debatable, though. Some people say that it is a waste of time and that 99% of users will not notice any difference. On the other hand, many expert typographers and typeface designers say it is a good thing to do, and I feel the extra time and emphasis given to marks, lead to better typographic communication.

Bruce Mau says this in his book, Life Style:

“Typographic design is the controlled release of information events in time. It operates on two temporal registers. The smallest is the shifting present tense of the reader. The largest is the sweep of historical time. Typography allows us to experience past and present simultaneously.

Every typographic decision — font, size, position, orientation, weight, colour, style — affects the reader’s speed of access, the rate at which the message is engaged by the nervous system.”

Bruce Mau says that people who design the reading experience are shapers of space and time. Furthermore, Peter Glaab says:

If the importance of a correctly punctuated sentence had seemed negligible to you, this will perk up your ears. Three arguments speak clearly for that:
  1. The text reads better.
  2. The text looks better.
  3. Correct orthography (the conventional spelling system of a language) enhances the value of a text.

Another analogy is timing and space in music. How could we say that empty and quiet spaces in music, or the contrast between loud (positive) and quiet (negative) sounds, do not matter? We cannot. These aspects are integral to it. White space is essential to so much design. Think about what information would look like without it? Erik Spiekermann once said:

You don’t actually design the black, you design the white: the space inside it and the space around it.

The control of white space in typography, and much of graphic communication, is design. It is as important as the black (positive) values. The spacing of punctuation marks and other symbols works more in an unconscious manner, rather than being directly perceivable, but it does have an effect.

What White Spaces In Typography Can We Use? Figure 2: A graphic representation of spaces available to use, from Yves Peters’ Adventures in Space: Spaces. A kerning value of any size can also be used (more on that later). (Large preview)

How do we know what width of space to add? Personal expertise plays a lot into it. I couldn’t imagine the need to use a space larger than a ¼ em (a quarter space). In his book, “The Elements Of Typographic Style,” Robert Bringhurst says:

“Kern consistently and modestly or not at all.”

Roland Stieger notes:

“We do not always use the same spaces, because every typeface has a different kerning. GREP (standing for: globally search a regular expression and print) we use only for bigger amounts of texts. In short texts, we often do it by hand (manually). With some fonts I find a hair space is fine, sometimes I find a thin space better. It really depends on the typeface.” What Punctuation Marks And Other Symbols Should We Add Spacing To?

Typographers usually add space to the left side of the following marks:

: ; ” ’ ! ? / ) ] } * ¿ › » @ ® ™ ℓ ° ¡ ' " † + = ÷ - – —

And they usually add space to the right of these:

“ ‘ / ( [ { > ≥ < ≤ £ $ ¢ € ‹ « √ μ # @ + = ÷ - – —

Upon further inspection of figure 2, we see that many more characters and symbols might need extra spacing, on the left or right side.

Figure 3 cropped (click/tap figure to see in full): My spacing and kerning test with gobbledygook text, with no additional spacing applied. Typeface size is 12 points, with 16-point leading. Default setting (tracking: 0; manual kerning: none applied; justification: desired, 100%). Baskerville Regular (version 13.0d1e10, which comes with macOS Catalina 10.15.2) old-style figures are not available in this version. (Large preview) Figure 4 cropped (click/tap figure to see in full): This uses the same typesetting as figure 3, but I have used a hair space (marked in light yellow) in InDesign to add better and wider spacing to select punctuation marks and many other symbols. (A hair space is 1/24th of an em, and an em is basically a square size of the body text — 12 points, in this case.) Notice how these marks have more space on the left and right side. You might not have consciously noticed it at first. (Large preview)


Figure 5: A real-time example of micro-typography. This interactive version of figure 4 allows you to change the spaces and see in real-time what has been adjusted. (View in a new window)

Figure 6 cropped (click/tap figure to see in full): This text block is the same as in figure 4. However, as you can see in both instances (figures 3 and 4), the typeface has kerning issues, which still need fixing. I have highlighted the kerning and baseline-shifting issues that need fixing in dark yellow. (Large preview)

So, in figures 3 to 6, we have seen what the spacing of punctuation and other symbols looks like. It is clear to me that this extra spacing makes for better and smoother typographic communication. We also see that not enough has been done by the typeface designer to apply white space and kerning, because many punctuation marks and other symbols are almost flush with the left or right character.

Examples Of Default Punctuation And Symbol Spacing In Different Typefaces

Are all typefaces the same, and do they have the same spacing of punctuation marks and other symbols from the left and right? The answer is no. Below are some examples of typefaces with their default settings (no tracking or kerning applied within the figures). Notice the white space around marks and non-alphabetic characters.

Figure 7 cropped (click/tap figure to see in full): Fira Sans Regular (version 4.301); typeface size: 9.2 points; leading: 16 points. Default settings (tracking: 0; manual kerning: none applied; justification: desired, 100%). Notice the better spacing and kerning built into this typeface by default than the Baskerville in figures 3, 4, and 6. Many fewer kerning and spacing issues are present in this typeface, and many of the default kerning settings do not need to be fixed. Good examples of default kerning are: ʺ} and +0–100 and 1:1 and //. (Large preview) Figure 8 cropped (click/tap figure to see in full): Spectral Regular (version 1.002); typeface size: 11 points; leading 16 points. Default settings (tracking: 0; manual kerning: none applied; justification: desired, 100%). Notice the wide kerning/spacing of characters, such as: “, ”, ‘, ’, : and ; by default. (Large preview) Figure 9 cropped (click/tap figure to see in full): Fira Mono Regular (version 3.206); typeface size: 9.2 points; leading: 16 points. I have included a monospace typeface to show that in monospace typefaces, all glyphs have the same width, and all characters or symbols align vertically. This leads to some interesting spacing characteristics and problems. (Large preview)

In figure 7, we can see that the default tracking (the spacing of letters across lines) for Fira Sans Regular is a little tight. In figure 8, we can see that Spectral Regular, a serif typeface for extended reading, has quite a lot of tracking across lines by default. If we look at a typeface like FF Unit, it also has quite a lot of tracking across lines by default. Much less spacing of punctuation marks and other symbols is needed, because the tracking is already generous. If we go to an extreme, like in figure 9, which uses Fira Mono Regular, you can see that, because all characters take up the same width, they all align vertically, creating a lot of white space on the left and right sides; thus, the spacing of punctuation marks and other symbols is not relevant.

So, we can now start to see that properly spacing punctuation marks and other symbols is a good thing to do, that there is some benefit, and we can see roughly what marks and symbols to add space to. But what are the issues faced by real-world practical designers whose clients do not have an unlimited budget?

The Current State Of Problems

Currently, addressing the issue is an ordeal and time-consuming. The problems can be summarized as follows:

  • Spacing punctuation marks and other symbols takes too much time, via any method.
  • Find-and-replace or GREP can produce a massive number of errors and is a solution just waiting to go wrong.
  • Modifying the typeface’s built-in kerning values is not easy to do or a best practice.
  • White space and kerning on web pages require (as of 2020) a lot of work to do and lacks technical support.
  • White space and kerning in eBooks end up having to be deleted and stripped out before the books are exported, or else they produce problems and empty (tofu) boxes □.
  • Modifying a typeface’s built-in sidebearing values is not easy to do or a best practice.
The Issues In More Detail Spacing Punctuation Marks And Other Symbols Takes Too Much Time

For a 30-page A5 book, you can pretty much do what you like. Spacing and kerning can be done manually, with little time added to the total typesetting cost. What about a 300-page academic book? Manually adding spaces in Adobe InDesign or Quark would be too time-consuming. What about a website? If done in Adobe Dreamweaver, you could open up all individual pages and then add spacing characters, such as hair spaces and thin spaces (see figure 2). Some people and organisations are willing to pay extra for this typographic quality, but they are rare. Nicky Barneby, in TypoGraphic 59, outlines Penguin’s composition rules, set by Jan Tschichold in 1946. What we as typographers need is some way to add spacing to an agreed-upon list of characters and symbols, and that would take no more than 15 minutes to implement for a lengthy book or website. This would be the ideal solution, and this is my goal.

Find-And-Replace And GREP Is Just Waiting To Go Wrong

It is possible to add white space and to adjust kerning values using the find-and-replace option in software (Adobe InDesign, Quark, Microsoft Word, Adobe Dreamweaver).

You could manually find-and-replace, and find-and-replace, and so on. This would allow you to see what changes are occurring. But doing this for an entire book or website and for all character and symbol combinations would take days and would add massively to the overall time and cost of typesetting.

Alternatively, you could use GREP (globally search a regular expression and print), as Ralf Herrmann demonstrates for Adobe InDesign. However, there are issues with this. I am not prepared to do a mass find-and-replace without seeing what the find-and-replace is actually doing to the text. I suspect there are people who are comfortable clicking the “Change all” button, but I am not one of them. The risk only increases when you are working on typography for a client, when mistakes and leaving it up to software could be disastrous.

Also, GREP is too technical for people who do not know how to code or who don’t know what code expressions are needed. And we would be heavily relying on the software knowing what we want (never a good idea). A lot can go wrong with changes that you do not see being done. Bram de Does (who some say has designed the world’s two most beautiful typefaces) puts it thus:

“I like to do manual things as much as possible.” Figure 10: The find-and-change window in Quark (left) and in Adobe InDesign (right). (Large preview)

Another issue is that, if we use a single hair space throughout a book or website, what happens if we want to increase it to a thin space? Well, we could do a find-and-replace for all hair spaces, and change them all to thin spaces in one click. That might work, but it might not. What happens if somewhere we have used two hair spaces side by side? When we do a find-and-replace, those two hair spaces would become two thin spaces. Two thin spaces are much wider than two hair spaces. Things get messy and complex quickly. Find-and-replace is a solution just waiting to go wrong.

Modifying A Typeface’s Built-in Kerning Values?

Kerning basically refers to the changing of space between two letters or symbols. Letterspacing (also known as tracking) refers to the addition or reduction of space across letters and symbols, across a line or lines of text. Every typeface has built within it (and specified by the typeface designer) a table of letter combinations and kerning values. Robert Bringhurst, in his book The Elements of Typographic Style, suggests another solution:

“One way to refine the typography of a text is to work your way through it line by line, putting space in here, removing it there, and repositioning errant characters one by one. But if these refinements are made to the font itself, you will never need to make them again. They are done for good.”

What he is suggesting is that we edit the kerning values or sidebearings (more on those in a minute) within the typeface itself, opening the font in typeface design software, and making the changes for good. I would not recommend this, for two reasons:

  1. The importing options alone in typeface software are beyond an academic exercise and will result in problems if not done properly by an expert. Typefaces produced before around 2004 were simpler to import and much less complex than typefaces available today. Much less could go wrong, technically and technologically, with typefaces built around 2004. When we add variable-font settings and issues with importing and modifying typefaces, errors are guaranteed to happen.
  2. Many typeface licences would class adjustments to the built-in kerning values and sidebearings in the typeface file itself as modifications, which would not be allowed in the end-user licence agreement (EULA). Doing it to open-source typefaces might be slightly more allowable, as Richard Hendel suggests, although still not guaranteed.

Furthermore, in Adobe InDesign, for example, if we take a character combination of A”, the A and closing quotation mark have a kerning value of -32. So, let’s say that we were going to add space to our selected list of marks using a +30 unit. For A”, which has a kerning value of -32, we could make that -2. This is easy to numerically work out and to space in increments or decrements of 30 units. However, what happens if the value was originally -26. We can work out the math, but how quickly? And it could increase complexity.

Quark’s Kerning Table Editing Feature

For many years, surprisingly, Quark has had a kerning table editing option, something that Adobe InDesign does not offer. It allows you to select a typeface and single weight, and then input a kerning pair to modify and customise on top of, overriding the built-in kerning table. In the “Kerning Pair” box, you input two characters to kern. In the “With-Stream” box, you can increase or decrease the horizontal amount in increments of 10 units. And in the “Cross-Stream” box, you can increase or decrease the vertical amount (similar to a baseline shift) in increments of 10 units. The modified kerning pair and value are then applied throughout the Quark document. Quark’s kerning table editing is a very interesting feature and can save a lot of time. Your customisations can also be saved and exported. Great! Now we’re talking. This option is getting us closer to our ideal scenario.

Figure 11: A screenshot of Quark’s kerning table editing option. (Large preview) White Space And Kerning On Web Pages Currently Requires A Lot Of Work And Lacks Technical Support

We could add spacing to punctuation marks and other symbols in two ways:

  1. We could use a range of white space characters, specifying the HTML or XML entity in the markup, as shown in figure 2 and as Yves Peters describes excellently.
  2. We could create two CSS classes, one for adding a unit of space to the left side, and one to the right side. Then, we would use a span tag to apply it to a letter or symbol.

Both options above are possible, but when you have to do this for hundreds of web pages, it becomes daunting and unmanageable.

If we want to kern on the web officially, we are somewhat limited in options. There are basically two CSS options out of the box: font-kerning: normal, which says to use the typeface’s built-in kerning, and font-kerning: none, which says not to use the typeface’s built-in kerning. The Mozilla Developer Network documentation has an example. Hardly useful.

However, let’s go back to our example of the letter combination A”, which have a kerning value of -32. If we were to use a hair space throughout (rather than a kerning value), at least there would be little math to do, because all of the white space characters (essentially a glyph) have a fixed value. So, one of the upsides of white spaces is that they have a consistent width value.

White Space And Kerning In eBooks Produce Tofu Characters

Adding white spaces to text and entities such as non-breaking spaces and non-breaking hyphens can create problems when the document is exported to an eBook format. It can create empty (tofu) □ characters. These spaces are probably best removed (stripped out) before you export to an eBook or HTML. Moreover, kerning in eBooks can only be specified from the typeface’s built-in values and cannot be modified or overridden. Once again, all of this decreases our options.

Modifying A Typeface’s Built-in Sidebearing Values?

Sidebearings refer to the horizontal fixed space on either side of an individual character or symbol. Whereas kerning modifies the space between two letters and many different letter and symbol combinations, sidebearings are like fixed concrete blocks on the left and ride sides, and the width. And when the value is set, it affects all instances of the letter or symbol where it is used, along with the kerning values applied on top of it. The spaces on either side are referred to as left sidebearing (LSB) and right sidebearing (RSB). These spaces ensure that characters sit beside one another with an even appearance. Essentially, it is the space to the left and right side of a character, before kerning is applied.

If you look back at figure 9 in this article, I used Fira Mono Regular for the text. If you scan down the text block, you’ll notice that all letters align vertically. The reason is that, essentially, all monospace typefaces have the same left and right sidebearings, or width bearing. (That is why it is called a monospace typeface — “mono”, as in singular). However, non-monospace typefaces have different left and right sidebearings; they span a character or symbol’s entire width. Good sidebearings can make the task of kerning a typeface easier. In Robert Bringhurst’s quote previously mentioned above, he basically says: If you fix it once, then it never needs fixing again. Perhaps, instead of adjusting the kerning, what we need to do is modify the sidebearing. Below is a screenshot from a panel in FontLab VI’s software Manual Metrics Editing.

Figure 12: FontLab VI’s Manual Metrics Editing panel. (Large preview)

This screenshot tells us a few things:

  1. The e (highlighted in the software) has a width bearing of 591 units, which is shown by the black thin vertical line to the left and right of the e.
  2. The left sidebearing of the e has 68 units.
  3. The right sidebearing of the e has 53 units.

So, if we were to think about the spacing and kerning issues mentioned earlier, let’s consider the colon (:). We always want a bit more space on the left of the colon, so that it is a bit set away from any character to its left. In theory, we could edit the left sidebearing and say that we want a bit more space on the left:

68 units + 20 units = 88 units

Note: This might equate to the space provided by a hair space, for example.

Then, every time the character gets used, in combination with other characters, it will always have a bit more space on the left. Is that it? Are we done? Not quite.

Consider this text: 1:1. What happens, now that we have increased the default left sidebearing, it could look like 1 :1. What we might need to do is add a kerning pair value for a 1: combination (although I am not an expert, and my knowledge is slightly lacking in this area).

This article has gotten quite technical, and I have probably confused and bored you by now. But hold on: there are potentially easier and clearer options.

Possibly Better Solutions White Space Edit For Print And Web To clarify: Adding white spaces is basically adding a white space character (entity).

What would a white space edit look like? Quark has a kerning table editing option; why doesn’t InDesign have one. What would it look like in CSS or via the syntax for OpenType features in CSS? What do we ideally need?

  1. The typographer would need to be able to define an agreed-upon preset list of punctuation marks and symbols to add space to.
  2. Having defined the preset list of punctuation marks and symbols to add space to, the user would then need to be able to specify which punctuation marks and symbols they want to add space to on the right side or left side.
  3. The user would then need to be able to specify problematic letter and symbol combinations; for example, to exclude adding space to text such as a URL: https://www. We might reasonably add space to the left and right of a forward slash sign (/), but with a combination like https://, we would get a customized double space to the right of the first / and to the left of the second /, making it look like this: https:/ /.
  4. When the user has done this, they would then need to be able to add a space that is user-definable, or a space value from, say, four options. For print: 25, 50, 75, 100 (measured 1/1000 em in InDesign, relative to the typeface’s size). And for web, maybe: 1px, 2px, 3px, 4px.
  5. The user would need to be able to apply this spacing to the style sheet in InDesign or Quark, and also in CSS. I am sure experts can think of better coding than what is below, but here is my amateurish attempt:
    .class { font-feature-settings-space-characters-symbols-left-side: value,value,value,value; /* Characters and symbols could be copied into the horizontal list, or Unicode HTML entity values used as well */ font-feature-settings-space-characters-symbols-right-side: value,value,value,value; /* Characters and symbols could be copied into the horizontal list, or Unicode HTML entity values used as well */ font-feature-settings-space-characters-symbols-amount: value; /* Any range of measuring units could be used: px, em, rem */ font-feature-settings-space-characters-symbols-problem-exclude-combinations: value,value,value,value; /* Letter and symbol combinations to not apply the above spacing to */ }
    Or leave it to typeface designer to allow four options built into their typeface, via OpenType Feature File Specification rules:
    font-feature-settings-space-characters-symbols-amount-space: value; /* The user is allowed to define 1 of a range of 4 values: quarter 1/4, half 1/2, two-thirds 2/3, full 4/4 */
    Note: I tried to pick up on the syntax for OpenType features in CSS.

  6. In Adobe InDesign and a website’s CSS, a user needs some method to edit white space, overriding the built-in values in print and web fonts, applying it to a paragraph or character style sheet or as a selector in a CSS class.
Kerning Table Editing For Print And Web To clarify: Kerning is the customization of space in between two letters or symbols. Kerning values are stored in a font file in a kerning table (kerning can also be applied and customized via software and stored within software). Kerning values override the three sidebearing values (left sidebearing, width bearing, and right sidebearing). Kerning can also be customised on top of the built-in kerning table through software like Adobe InDesign and Quark. Letterspacing (also known as tracking) is a consistent positive (+) or negative (-) space value applied across a whole line of text.

What would a kerning table edit in Adobe InDesign look like? Quark has one. What would it look like in CSS or in the syntax for OpenType features in CSS? What do we ideally need? Well, in InDesign, it could look something like figure 11, pushed a bit further. Kerning typically relates to the space between two characters. For the spacing of punctuation and other marks, we are interested in spacing, but how would we kern all instances of a character and a colon (:), like the following: a:, b:, c:? We would be doing it for a long time, because there are potentially thousands of combinations that use a colon. However, if we could specify one character in the kerning pair dialog box (as shown in figure 11), then maybe we could specify a character and just say we want +25 units on the left side. For a kerning table edit on the web, we could do something like what’s shown below (but, again, we really need some way to read a font’s built-in kerning values, because we have no idea what they are to begin with):

fontname kerningtable { /* Accesses the kerning table within the web font file. */ font-feature-settings-kerning-table-edit: character character, -value or +value; /* The user selects two characters to kern, and then specifies a negative or positive value in a measurement unit (px, em, etc.). */ font-feature-settings-kerning-table-edit-direction: horizontal or vertical; /* The user can specify whether they want the kerning to be horizontal or vertical. */ } Sidebearing Edit For Print And Web To clarify: Sidebearings differ from kerning because they act like bottom-level (non-overridable) concrete blocks, forming the width of all the individual letters and symbols. A sidebearing value affects all instances of the letter or symbol where it is used, and the kerning values are applied on top of it. So, a lowercase i has a narrower width sidebearing than a lowercase m, which is twice as wide as an i (for non-monospace typefaces in general).

What would a sidebearing edit in Adobe InDesign look like? What would it look like in CSS or via the syntax for OpenType features in CSS? What do we ideally need? Well, it would look much like the example given under the heading above for “White space edit for print and web”. We would need some way to read the built-in sidebearing. So, in figure 12, the left sidebearing is 68, the right sidebearing is 53, and the width is 591. In CSS, we would somehow need to obtain the three built-in values for any character or symbol, either from an official public source or from the font maker. Then, maybe we could override those values using CSS:

fontname character { /* Accesses the sidebearing values within the web font file. */ font-feature-settings-sidebearing-for-what-character: character; /* The user can paste in the character or specify a decimal or HEX entity. */ font-feature-settings-left-sidebearing: value; /* Value in px? */ font-feature-settings-right-sidebearing: value; /* Value in px? */ font-feature-settings-width-sidebearing: value; /* Value in px? */ font-feature-settings-sidebearing-problem-exclude-combinations: value; /* Letter and symbol combinations to not apply the above spacing to */ } Observations

If you have read this far and have not given up or gotten bored, then you are clearly a committed typographer.

Let’s conclude:

  • Adding space characters (which are essentially character entities) of any kind, like hair spaces or thin spaces, in any software (Adobe InDesign, Quark, HTML) just leads to problems and results in a load of work.
  • We need to be able to modify spacing via the actual kerning value, rather than via a white space character or entity.
  • Typographers need to be able to override the built-in kerning table values in typefaces, then be able to apply custom kerning values via access to a kerning table editing feature.
  • Users need to be able to apply spacing to punctuation marks and other select symbols, and apply custom kerning globally to a typeface (either a desktop or web font), via a paragraph or character style sheet in Adobe InDesign and CSS. We need to be able to do all of this in a print document or website in less than 15 minutes, and it needs to be easy enough for people with basic software knowledge to do.
What Might The Solution Look Like?

Should the OpenType Feature File Specification rules allow for the spacing of punctuation marks and other symbols, so that typeface designers can allow it via some kind of OpenType pre-built option within their typefaces before releasing them for sale? Should Adobe InDesign have some kind of built-in kerning table editing, like Quark has had for many years? Should CSS allow access to a typeface’s built-in kerning table, for custom values to override the designer’s values? Should typeface designers space punctuation marks and other symbols better and more generously? Have they been lacking attention in this area?

Figure 13: Modified screenshot from Adobe InDesign’s OpenType options panel. Can we not add some option in the OpenType panel to add spacing to a selection of characters and symbols on the left or right side, as illustrated? (Large preview) Figure 14: Modified screenshot from an Adobe InDesign panel, showing a potential new feature. When you modify a metric kerning value, there would be an option to apply it globally for an individual typeface’s style and weight. (Large preview) Afterword

I hope you have found this article insightful and useful. I have not presented a perfect solution, but rather have covered potentially viable solutions, which I am happy to be developed and explored further. I am no expert in internal typeface kerning, technology, or new CSS properties. But I am sure we can do something about these hard-to-manage spacing problems that typographers and typesetters have been dealing with for so many hundreds of years across changing technological media. If you have any ideas, contact me by visiting the website linked in my “About the Author” page shown at the top of this article.

Thanks to Rachel Andrew (for advice and editing), Erik Spiekermann (for email support and further contacts), and Jost Hochuli and Roland Stieger (for support and feedback).

“I would love all those features, but I only know 1 or 2 other graphic designers who would use them. They don’t even use any of the OpenType features or Stylistic sets. I used the kerning table edit in Quark all the time, when setting different languages. Partly because I didn’t like some of the built-in kernings, partly because there were some missing, especially those after and before spaces. But most designers don’t even change the default word spaces in InDesign, let alone bother about more details. Sad, but ask other typeface designers and the few good typesetters out there: standards are low.”

Erik Spiekermann (March 2020) Further Reading (ra, yk, il, al)
Categories: Web Design

Setting TypeScript For Modern React Projects Using Webpack And Babel

Smashing Magazine - Mon, 05/11/2020 - 03:30
Setting TypeScript For Modern React Projects Using Webpack And Babel Setting TypeScript For Modern React Projects Using Webpack And Babel Blessing Krofegha 2020-05-11T10:30:00+00:00 2020-05-20T10:51:42+00:00

In this era of software development, JavaScript can be used to develop almost any type of app. However, the fact that JavaScript is dynamically typed could be a concern for most large enterprise companies, because of its loose type-checking feature.

Fortunately, we don’t have to wait until the Ecma Technical Committee 39 introduces a static type system into JavaScript. We can use TypeScript instead.

JavaScript, being dynamically typed, is not aware of the data type of a variable until that variable is instantiated at runtime. Developers who write large software programs might have a tendency to reassign a variable, declared earlier, to a value of a different type, with no warning or issue whatsoever, resulting in bugs often overlooked.

In this tutorial, we will learn what TypeScript is and how to work with it in a React project. By the end, we’ll have built a project consisting of an episode-picker app for the TV show Money Heist, using TypeScript and current React-like hooks (useState, useEffect, useReducer, useContext). With this knowledge, you can go on to experiment with TypeScript in your own projects.

This article isn’t an introduction to TypeScript. Hence, we won’t go through the basic syntax of TypeScript and JavaScript. However, you don’t have to be an expert in any of these languages to follow along, because we’ll try to follow the KISS principle (keep it simple, stupid).

What Is TypeScript?

In 2019, TypeScript was ranked the seventh most-used language and the fifth fastest-growing language on GitHub. But what exactly is TypeScript?

According to the official documentation, TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It is developed and maintained by Microsoft and the open-source community.

“Superset” in this context means that the language contains all of the features and functionality of JavaScript and then some. TypeScript is a typed scripting language.

It offers developers more control over their code base via its type annotation, classes, and interface, sparing developers from having to manually fix annoying bugs in the console.

TypeScript wasn’t created to alter JavaScript. Instead, it expands on JavaScript with valuable new features. Any program written in plain JavaScript will also run as expected in TypeScript, including cross-platform mobile apps and back ends in Node.js.

This means you can also write React apps in TypeScript, as we will do in this tutorial.

Why TypeScript?

Perhaps, you aren’t convinced of embracing the goodness of TypeScript. Let’s consider a few of its advantages.

Fewer Bugs

We cannot eliminate all bugs in our code, but we can reduce them. TypeScript checks for types at compile-time and throws errors if the variable type changes.

Being able to find these obvious yet frequent errors this early on makes it a lot easier to manage your code with types.

Refactoring Is Easier

You probably often want to refactor quite a lot of things, but because they touch so much other code and many other files, you’re wary of modifying them.

In TypeScript, such things can often be refactored with just a click of the “Rename symbol” command in your integrated development environment (IDE).

Renaming app to expApp (Large preview)

In a dynamically typed language such as JavaScript, the only way to refactor multiple files at the same time is with the traditional “search and replace” function using regular expressions (RegExp).

In a statically typed language such as TypeScript, “search and replace” isn’t needed anymore. With IDE commands such as “Find all occurrences” and “Rename symbol”, you can see all occurrences in the app of the given function, class, or property of an object interface.

TypeScript will help you find all instances of the refactored bit, rename it, and alert you with a compile error in case your code has any type mismatches after the refactoring.

TypeScript has even more advantages than what we’ve covered here.

Disadvantages Of TypeScript

TypeScript is surely not without its disadvantages, even given the promising features highlighted above.

A False Sense Of Security

TypeScript’s type-checking feature often creates a false sense of security among developers. The type checking indeed warns us when something is wrong with our code. However, static types don’t reduce overall bug density.

Therefore, the strength of your program will depend on your usage of TypeScript, because types are written by the developer and not checked at runtime.

If you’re looking to TypeScript to reduce your bugs, please consider test-driven development instead.

Complicated Typing System

The typing system, while a great tool in many regards, can sometimes be a little complicated. This downside stems from it being fully interoperable with JavaScript, which leaves even more room for complication.

However, TypeScript is still JavaScript, so understanding JavaScript is important.

When To Use TypeScript?

I would advise you to use TypeScript in the following cases:

  • If you’re looking to building an application that will be maintained over a long period, then I would strongly recommend starting with TypeScript, because it fosters self-documenting code, thus helping other developers to understand your code easily when they join your code base.
  • If you need to create a library, consider writing it in TypeScript. It will help code editors to suggest the appropriate types to developers who are using your library.

In the last few sections, we have balanced the pros and cons of TypeScript. Let’s move on to the business of the day: setting up TypeScript in a modern React project.

Getting Started

There are several ways to set up TypeScript in a React Project. In this tutorial, we’ll be covering just two.

Method 1: Create React App + TypeScript

About two years ago, the React team released Create React App 2.1, with TypeScript support. So, you might never have to do any heavy lifting to get TypeScript into your project.

Announcement of TypeScript in Create React App (Large preview)

To start a new Create React App project, you can run this…

npx create-react-app my-app --folder-name

… or this:

yarn create react-app my-app --folder-name

To add TypeScript to a Create React App project, first install it and its respective @types:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

… or:

yarn add typescript @types/node @types/react @types/react-dom @types/jest

Next, rename the files (for example, index.js to index.tsx), and restart your development server!

That was quick, wasn’t it?

Method 2: Set Up TypeScript With Webpack

Webpack is a static module bundler for JavaScript applications. It takes all of the code from your application and makes it usable in a web browser. Modules are reusable chunks of code built from your app’s JavaScript, node_modules, images, and CSS styles, which are packaged to be easily used on your website.

Create A New Project

Let’s start by creating a new directory for our project:

mkdir react-webpack cd react-webpack

We’ll use npm to initialize our project:

npm init -y

The command above will generate a package.json file with some default values. Let’s also add some dependencies for webpack, TypeScript, and some React-specific modules.

Installing Packages

Lastly, we’d need to install the necessary packages. Open your command-line interface (CLI) and run this:

#Installing devDependencies npm install --save-dev @types/react @types/react-dom awesome-typescript-loader css-loader html-webpack-plugin mini-css-extract-plugin source-map-loader typescript webpack webpack-cli webpack-dev-server #installing Dependencies npm install react react-dom

Let’s also manually add a few different files and folders under our react-webpack folder:

  1. Add webpack.config.js to add webpack-related configurations.
  2. Add tsconfig.json for all of our TypeScript configurations.
  3. Add a new directory, src.
  4. Create a new directory, components, in the src folder.
  5. Finally, add index.html, App.tsx, and index.tsx in the components folder.
Project Structure

Thus, our folder structure will look something like this:

├── package.json ├── package-lock.json ├── tsconfig.json ├── webpack.config.js ├── .gitignore └── src └──components ├── App.tsx ├── index.tsx ├── index.html Start Adding Some Code

We’ll start with index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>React-Webpack Setup</title> </head> <body> <div id="output"></div> </body> </html>

This will create the HTML, with an empty div with an ID of output.

Let’s add the code to our React component App.tsx:

import * as React from "react"; export interface HelloWorldProps { userName: string; lang: string; } export const App = (props: HelloWorldProps) => ( <h1> Hi {props.userName} from React! Welcome to {props.lang}! </h1> );

We’ve created an interface object and named it HelloWorldProps, with userName and lang having a string type.

We passed props to our App component and exported it.

Now, let’s update the code in index.tsx:

import * as React from "react"; import * as ReactDOM from "react-dom"; import { App } from "./App"; ReactDOM.render( <App userName="Beveloper" lang="TypeScript" />, document.getElementById("output") );

We just imported the App component into index.tsx. When webpack sees any file with the extension .ts or .tsx, it will transpile that file using the awesome-typescript-loader library.

TypeScript Configuration

We’ll then add some configuration to tsconfig.json:

{ "compilerOptions": { "jsx": "react", "module": "commonjs", "noImplicitAny": true, "outDir": "./build/", "preserveConstEnums": true, "removeComments": true, "sourceMap": true, "target": "es5" }, "include": [ "src/components/index.tsx" ] }

Let’s also look at the different options we added to tsconfig.json:

  • compilerOptions Represents the different compiler options.
  • jsx:react Adds support for JSX in .tsx files.
  • lib Adds a list of library files to the compilation (for example, using es2015 allows us to use ECMAScript 6 syntax).
  • module Generates module code.
  • noImplicitAny Raises errors for declarations with an implied any type.
  • outDir Represents the output directory.
  • sourceMap Generates a .map file, which can be very useful for debugging the app.
  • target Represents the target ECMAScript version to transpile our code down to (we can add a version based on our specific browser requirements).
  • include Used to specify the file list to be included.
Webpack Configuration

Let’s add some webpack configuration to webpack.config.js.

const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { entry: "./src/components/index.tsx", target: "web", mode: "development", output: { path: path.resolve(\__dirname, "build"), filename: "bundle.js", }, resolve: { extensions: [".js", ".jsx", ".json", ".ts", ".tsx"], }, module: { rules: [ { test: /\.(ts|tsx)$/, loader: "awesome-typescript-loader", }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader", }, { test: /\.css$/, loader: "css-loader", }, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(\__dirname, "src", "components", "index.html"), }), new MiniCssExtractPlugin({ filename: "./src/yourfile.css", }), ], };

Let’s look at the different options we’ve added to webpack.config.js:

  • entry This specifies the entry point for our app. It may be a single file or an array of files that we want to include in our build.
  • output This contains the output configuration. The app looks at this when trying to output bundled code from our project to the disk. The path represents the output directory for code to be outputted to, and the file name represents the file name for the same. It is generally named bundle.js.
  • resolve Webpack looks at this attribute to decide whether to bundle or skip the file. Thus, in our project, webpack will consider files with the extensions .js, .jsx, .json, .ts , and .tsx for bundling.
  • module We can enable webpack to load a particular file when requested by the app, using loaders. It takes a rules object that specifies that:
    • any file that ends with the extension .tsx or .ts should use awesome-typescript-loader to be loaded;
    • files that end with the .js extension should be loaded with source-map-loader;
    • files that end with the .css extension should be loaded with css-loader.
  • plugins Webpack has its own limitations, and it provides plugins to overcome them and extend its capabilities. For example, html-webpack-plugin creates a template file that is rendered to the browser from the index.html file in the ./src/component/index.html directory.

MiniCssExtractPlugin renders the parent CSS file of the app.

Adding Scripts To package.json

We can add different scripts to build React apps in our package.json file:

"scripts": { "start": "webpack-dev-server --open", "build": "webpack" },

Now, run npm start in your CLI. If it all went well, you should see this:

React-Webpack setup output (Large preview)

If you have a knack for webpack, clone the repository for this setup, and use it across your projects.

Creating Files

Create a src folder and an index.tsx file. This will be the base file that renders React.

Now, if we run npm start, it will run our server and open a new tab. Running npm run build will build webpack for production and will create a build folder for us.

We have seen how to set up TypeScript from scratch using the Create React App and webpack configuration method.

One of the quickest ways to get a full grasp of TypeScript is by converting one of your existing vanilla React projects to TypeScript. Unfortunately, incrementally adopting TypeScript in an existing vanilla React project is stressful because it entails having to eject or rename all of the files, which would result in conflicts and a giant pull request if the project belonged to a large team.

Next, we’ll look at how to easily migrate a React project to TypeScript.

Migrate An Existing Create React App To TypeScript

To make this process more manageable, we’ll break it down into steps, which will enable us to migrate in individual chunks. Here are the steps we’ll take to migrate our project:

  1. Add TypeScript and types.
  2. Add tsconfig.json.
  3. Start small.
  4. Rename files extension to .tsx.
1. Add TypeScript to the Project

First, we’ll need to add TypeScript to our project. Assuming that your React project was bootstrapped with Create React App, we can run the following:

# Using npm npm install --save typescript @types/node @types/react @types/react-dom @types/jest # Using Yarn yarn add typescript @types/node @types/react @types/react-dom @types/jest

Notice that we haven’t changed anything to TypeScript yet. If we run the command to start the project locally (npm start or yarn start), nothing changes. If that’s the case, then great! We’re ready for the next step.

2. Add the tsconfig.json File

Before taking advantage of TypeScript, we need to configure it via the tsconfig.json file. The simplest way to get started is to scaffold one using this command:

npx tsc --init

This gets us some basics, with a lot of commented code. Now, replace all of the code in tsconfig.json with this:

{ "compilerOptions": { "jsx": "react", "module": "commonjs", "noImplicitAny": true, "outDir": "./build/", "preserveConstEnums": true, "removeComments": true, "sourceMap": true, "target": "es5" }, "include": [ "./src/**/**/\*" ] } TypeScript Configuration

Let’s also look at the different options we added to tsconfig.json:

  • compilerOptions Represents the different compiler options.
    • target Translates newer JavaScript constructs down to an older version, like ECMAScript 5.
    • lib Adds a list of library files to the compilation (for example, using es2015 allows us to use ECMAScript 6 syntax).
    • jsx:react Adds support for JSX in .tsx files.
    • lib Adds a list of library files to the compilation (for example, using es2015 allows us to use ECMAScript 6 syntax).
    • module Generates module code.
    • noImplicitAny Used to raise errors for declarations with an implied any type.
    • outDir Represents the output directory.
    • sourceMap Generates a .map file, which can be very useful for debugging our app.
    • include Used to specify the file list to be included.

Configurations options will vary, according to a project’s demand. You might need to check the TypeScript options spreadsheet to figure out what would fit your project.

We have only taken the required actions to get things ready. Our next step is to migrate a file to TypeScript.

3. Start With a Simple Component

Take advantage of TypeScript’s ability to be gradually adopted. Go one file at a time at your own pace. Do what makes sense for you and your team. Don’t try to tackle it all at once.

To properly convert this, we need to do two things:

  1. Change the file extension to .tsx.
  2. Add the type annotation (which would require some TypeScript knowledge).
4.Rename File Extensions to .tsx

In a large code base, it might seem tiring to rename files individually.

Rename multiples files on macOS

Renaming multiple files can be a time-waster. Here is how you can do it on a Mac. Right-click (or Ctrl + click, or click with two fingers simultaneously on the trackpad if you are using a MacBook) on the folder that contains the files you want to rename. Then, click “Reveal in Finder”. In the Finder, select all of the files you want to rename. Right-click the selected files, and choose “Rename X items…” Then, you will see something like this:

Rename files on a Mac (Large preview)

Insert the string you want to find, and the string with which you want to replace that found string, and hit “Rename”. Done.

Rename multiples files on Windows

Renaming multiple files on Windows is beyond the scope of this tutorial, but a complete guide is available. You would usually get errors after renaming the files; you just need to add the type annotations. You can brush up on this in the documentation.

We have covered how to set up TypeScript in a React app. Now, let’s build an episode-picker app for Money Heist using TypeScript.

We won’t cover the basic types of TypeScript. Going through the documentation before continuing in this tutorial is required.

Time to Build

To make this process feel less daunting, we’ll break this down into steps, which will enable us to build the app in individual chunks. Here are all of the steps we’ll take to build the Money Heist episode-picker:

  • Scaffold a Create React App.
  • Fetch episodes.
    • Create the appropriate types and interfaces for our episodes in interface.ts.
    • Set up store for fetching episodes in store.tsx.
    • Create the action for fetching episodes in action.ts.
    • Create an EpisodeList.tsx component that holds the episodes fetched.
    • Import the EpisodesList component to our home page using React Lazy and Suspense.
  • Add episodes.
    • Set up store to add episodes in store.tsx.
    • Create the action for adding episodes in action.ts.
  • Remove episodes.
    • Set up store for deleting episodes in store.tsx.
    • Create the action for deleting episodes in action.ts.
  • Favorite episode.
    • Import EpisodesList component in favorite episode.
    • Render EpisodesList inside favorite episode.
  • Using Reach Router for navigation.
Set Up React

The easiest way to set up React is to use Create React App. Create React App is an officially supported way to create single-page React applications. It offers a modern build setup with no configuration.

We’ll make use of it to bootstrap the application we’ll be building. From your CLI, run the command below:

npx create-react-app react-ts-app && cd react-ts-app

Once the installation is successful, start the React server by running npm start.

React starter page (Large preview) Understanding Interfaces And Types In Typescript

Interfaces in TypeScript are used when we need to give types to objects properties. Hence, we would be using interfaces to define our types.

interface Employee { name: string, role: string salary: number } const bestEmployee: Employee= { name: 'John Doe', role: 'IOS Developer', salary: '$8500' //notice we are using a string }

When compiling the code above, we would see this error: “Types of property salary are incompatible. Type string is not assignable to type number.”

Such errors happen in TypeScript when a property or variable is assigned a type other than the defined type. Specifically, the snippet above means that the salary property was assigned a string type instead of a number type.

Let’s create an interface.ts file in our src folder. Copy and paste this code into it:

/** |-------------------------------------------------- | All the interfaces! |-------------------------------------------------- */ export interface IEpisode { airdate: string airstamp: string airtime: string id: number image: { medium: string; original: string } name: string number: number runtime: number season: number summary: string url: string } export interface IState { episodes: Array<IEpisode> favourites: Array<IEpisode> } export interface IAction { type: string payload: Array<IEpisode> | any } export type Dispatch = React.Dispatch<IAction> export type FavAction = ( state: IState, dispatch: Dispatch, episode: IEpisode ) => IAction export interface IEpisodeProps { episodes: Array<IEpisode> store: { state: IState; dispatch: Dispatch } toggleFavAction: FavAction favourites: Array<IEpisode> } export interface IProps { episodes: Array<IEpisode> store: { state: IState; dispatch: Dispatch } toggleFavAction: FavAction favourites: Array<IEpisode> }

It’s a good practice to add an “I” to the name of the interface. It makes the code readable. However, you may decide to exclude it.

IEpisode Interface

Our API returns a set of properties such as airdate, airstamp, airtime, id, image, name, number, runtime, season, summary, and url. Hence, we defined an IEpisode interface and set the appropriate data types to the object properties.

IState Interface

Our IState interface has episodes and favorites properties, respectively, and an Array<IEpisode> interface.

IAction

The IAction interface properties are payload and type. The type property has a string type, while the payload has a type of Array | any.

Note that Array | any means an array of the episode interface or any type.

The Dispatch type is set to React.Dispatch and a <IAction> interface. Note that React.Dispatch is the standard type for the dispatch function, according to the @types/react code base, while <IAction> is an array of the Interface action.

Also, Visual Studio Code has a TypeScript checker. So, by merely highlighting or hovering over code, it’s smart enough to suggest the appropriate type.

In other words, for us to make use of our interface across our apps, we need to export it. So far, we have our store and our interfaces that hold the type of our object. Let’s now create our store. Note that the other interfaces follow the same conventions as the ones explained.

Fetch Episodes

Creating a Store

To fetch our episodes, we need a store that holds the initial state of the data and that defines our reducer function.

We’ll make use of useReducer hook to set that up. Create a store.tsx file in your src folder. Copy and paste the following code into it.

import React, { useReducer, createContext } from 'react' import { IState, IAction } from './types/interfaces' const initialState: IState = { episodes: [], favourites: [] } export const Store = createContext(initialState) const reducer = (state: IState, action: IAction): IState => { switch (action.type) { case 'FETCH_DATA': return { ...state, episodes: action.payload } default: return state } } export const StoreProvider = ({ children }: JSX.ElementChildrenAttribute): JSX.Element => { const [state, dispatch] = useReducer(reducer, initialState) return {children} }

The following are the steps we’ve taken to create the store:

  • In defining our store, we need the useReducer hook and the createContext API from React, which is why we imported it.
  • We imported IState and IAction from ./types/interfaces.
  • We declared an initialState object with a type of IState, and properties of episodes and favorites, which are both set to an empty array, respectively.
  • Next, we created a Store variable that holds the createContext method and that is passed the initialState.

The createContext method type is <IState | any>, which means it could be a type of <IState> or any. We will see the any type used often in this article.

  • Next, we declared a reducer function and passed in state and action as parameters. The reducer function has a switch statement that checks the value of action.type. If the value is FETCH_DATA, then it returns an object that has a copy of our state (...state) and of the episode state that holds our action payload.
  • In the switch statement, we return a state of default.

Note that the state and action parameters in the reducer function have IState and IAction types, respectively. Also, the reducer function has a type of IState.

  • Lastly, we declared a StoreProvider function. This will give all components in our app access to the store.
  • This function takes children as a prop, and inside the StorePrivder function, we declared the useReducer hook.
  • We destructured state and dispatch.
  • In order to make our store accessible to all components, we passed in an object value containing state and dispatch.

The state that contains our episodes and favorites state will be made accessible by other components, while the dispatch is a function that changes the state.

  • We will export Store and StoreProvider, so that it can be used across our application.
Create Action.ts

We’ll need to make requests to the API to fetch the episodes that will be shown the user. This will be done in an action file. Create an Action.ts file, and then paste the following code:

import { Dispatch } from './interface/interfaces' export const fetchDataAction = async (dispatch: Dispatch) => { const URL = 'https://api.tvmaze.com/singlesearch/shows?q=la-casa-de-papel&embed=episodes' const data = await fetch(URL) const dataJSON = await data.json() return dispatch({ type: 'FETCH_DATA', payload: dataJSON.\_embedded.episodes }) }

First, we need to import our interfaces so that they can be used in this file. The following steps were taken to create the action:

  • The fetchDataAction function takes dispatch props as a parameter.
  • Because our function is asynchronous, we would be using async and await.
  • We create a variable(URL) that holds our API endpoint.
  • We have another variable named data that holds the response from the API.
  • Then, we store the JSON response in dataJSON, after we have gotten the response in JSON format by calling data.json().
  • Lastly, we return a dispatch function that has a property of type and a string of FETCH_DATA. It also has a payload(). _embedded.episodes is the array of the episodes object from our endpoint.

Note that the fetchDataAction function fetches our endpoint, converts it to JSON objects, and returns the dispatch function, which updates the state declared earlier in the Store.

The exported dispatch type is set to React.Dispatch. Note that React.Dispatch is the standard type for the dispatch function according to the @types/react code base, while <IAction> is an array of the Interface Action.

EpisodesList Component

In order to maintain the reusability of our app, we will keep all fetched episodes in a separate file, and then import the file in our homePage component.

In the components folder, create an EpisodesList.tsx file, and copy and paste the following code to it:

import React from 'react' import { IEpisode, IProps } from '../types/interfaces' const EpisodesList = (props: IProps): Array<JSX.Element> => { const { episodes } = props return episodes.map((episode: IEpisode) => { return ( <section key={episode.id} className='episode-box'> <img src={!!episode.image ? episode.image.medium : ''} alt={`Money Heist ${episode.name}`} /> <div>{episode.name}</div> <section style={{ display: 'flex', justifyContent: 'space-between' }}> <div> Season: {episode.season} Number: {episode.number} </div> <button type='button' > Fav </button> </section> </section> ) }) } export default EpisodesList
  • We import IEpisode and IProps from interfaces.tsx.
  • Next, we create an EpisodesList function that takes props. The props will have a type of IProps, while the function has a type of Array<JSX.Element>.

Visual Studio Code suggests that our function type be written as JSX.Element[].

Visual Studio Code suggests a type (Large preview)

While Array<JSX.Element> is equal to JSX.Element[], Array<JSX.Element> is called the generic identity. Hence, the generic pattern will be used often in this article.

  • Inside the function, we destructure the episodes from props, which has the IEpisode as a type.

Read about the generic identity, This knowledge will be needed as we proceed.

  • We returned the episodes props and mapped through it to return a few HTML tags.
  • The first section holds the key, which is episode.id, and a className of episode-box, which will be created later. We know that our episodes have images; hence, the image tag.
  • The image has a ternary operator that checks if there’s either an episode.image or an episode.image.medium. Else, we display an empty string if no image is found. Also, we included the episode.name in a div.

In section, we show the season that an episode belongs to and its number. We have a button with the text Fav. We’e exported the EpisodesList component so that we can use it across our app.

Home Page Component

We want the home page to trigger the API call and display the episodes using the EpisodesList component we created. Inside the components folder, create the HomePage component, and copy and paste the following code to it:

import React, { useContext, useEffect, lazy, Suspense } from 'react' import App from '../App' import { Store } from '../Store' import { IEpisodeProps } from '../types/interfaces' import { fetchDataAction } from '../Actions' const EpisodesList = lazy<any>(() => import('./EpisodesList')) const HomePage = (): JSX.Element => { const { state, dispatch } = useContext(Store) useEffect(() => { state.episodes.length === 0 && fetchDataAction(dispatch) }) const props: IEpisodeProps = { episodes: state.episodes, store: { state, dispatch } } return ( <App> <Suspense fallback={<div>loading...</div>}> <section className='episode-layout'> <EpisodesList {...props} /> </section> </Suspense> </App> ) } export default HomePage
  • We import useContext, useEffect, lazy, and Suspense from React. The imported app component is the bedrock upon which all other components must receive the value of the store.
  • We also import Store, IEpisodeProps, and FetchDataAction from their respective files.
  • We import the EpisodesList component using the React.lazy feature available in React 16.6.

React lazy loading supports the code-splitting convention. Thus, our EpisodesList component is loaded dynamically, instead of being loaded at once, thereby improving the performance of our app.

  • We destructure the state and dispatch as props from the Store.
  • The ampersand (&&) in the useEffect hook checks if our episodes state is empty (or equal to 0). Else, we return the fetchDataAction function.
  • Lastly, we return the App component. Inside it, we use the Suspense wrapper, and set fallback to a div with the loading text. This will be displayed to the user while we await the response from the API.
  • The EpisodesList component will mount when the data is available, and the data that will contain the episodes is what we spread into it.
Set Up Index.txs

The Homepage component needs to be a child of the StoreProvider. We’ll have to do that in the index file. Rename index.js to index.tsx and paste the following code:

import React from 'react' import ReactDOM from 'react-dom' import './index.css' import { StoreProvider } from './Store' import HomePage from './components/HomePage' ReactDOM.render( <StoreProvider> <HomePage /> </StoreProvider>, document.getElementById('root') )

We import StoreProvider, HomePage, and index.css from their respective files. We wrap the HomePage component in our StoreProvider. This makes it possible for the Homepage component to access the store, as we saw in the previous section.

We have come a long way. Let’s check what the app looks like, without any CSS.

App without CSS (Large preview) Create Index.css

Delete the code in the index.css file and replace it with this:

html { font-size: 14px; } body { margin: 0; padding: 0; font-size: 10px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .episode-layout { display: flex; flex-wrap: wrap; min-width: 100vh; } .episode-box { padding: .5rem; } .header { display: flex; justify-content: space-between; background: white; border-bottom: 1px solid black; padding: .5rem; position: sticky; top: 0; }

Our app now has a look and feel. Here’s how it looks with CSS.

(Large preview)

Now we see that our episodes can finally be fetched and displayed, because we’ve adopted TypeScript all the way. Great, isn’t it?

Add Favorite Episodes Feature

Let’s add functionality that adds favorite episodes and that links it to a separate page. Let’s go back to our Store component and add a few lines of code:

Note that the highlighted code is newly added:

import React, { useReducer, createContext } from 'react' import { IState, IAction } from './types/interfaces' const initialState: IState = { episodes: [], favourites: [] } export const Store = createContext<IState | any>(initialState) const reducer = (state: IState, action: IAction): IState => { switch (action.type) { case 'FETCH_DATA': return { ...state, episodes: action.payload } case 'ADD_FAV': return { ...state, favourites: [...state.favourites, action.payload] } default: return state } } export const StoreProvider = ({ children }: JSX.ElementChildrenAttribute): JSX.Element => { const [state, dispatch] = useReducer(reducer, initialState) return <Store.Provider value={{ state, dispatch }}>{children}</Store.Provider> }

To implement the “Add favorite” feature to our app, the ADD_FAV case is added. It returns an object that holds a copy of our previous state, as well as an array with a copy of the favorite state, with the payload.

We need an action that will be called each time a user clicks on the FAV button. Let’s add the highlighted code to index.tx:

import { IAction, IEpisode, Dispatch } from './types/interfaces' export const fetchDataAction = async (dispatch: Dispatch) => { const URL = 'https://api.tvmaze.com/singlesearch/shows?q=la-casa-de-papel&embed=episodes' const data = await fetch(URL) const dataJSON = await data.json() return dispatch({ type: 'FETCH_DATA', payload: dataJSON._embedded.episodes }) } export const toggleFavAction = (dispatch: any, episode: IEpisode | any): IAction => { let dispatchObj = { type: 'ADD_FAV', payload: episode } return dispatch(dispatchObj) }

We create a toggleFavAction function that takes dispatch and episodes as parameters, and any and IEpisode|any as their respective types, with IAction as our function type. We have an object whose type is ADD_FAV and that has episode as its payload. Lastly, we just return and dispatch the object.

We will add some more snippets to EpisodeList.tsx. Copy and paste the highlighted code:

import React from 'react' import { IEpisode, IProps } from '../types/interfaces' const EpisodesList = (props: IProps): Array<JSX.Element> => { const { episodes, toggleFavAction, favourites, store } = props const { state, dispatch } = store return episodes.map((episode: IEpisode) => { return ( <section key={episode.id} className='episode-box'> <img src={!!episode.image ? episode.image.medium : ''} alt={`Money Heist - ${episode.name}`} /> <div>{episode.name}</div> <section style={{ display: 'flex', justifyContent: 'space-between' }}> <div> Seasion: {episode.season} Number: {episode.number} </div> <button type='button' onClick={() => toggleFavAction(state, dispatch, episode)} > {favourites.find((fav: IEpisode) => fav.id === episode.id) ? 'Unfav' : 'Fav'} </button> </section> </section> ) }) } export default EpisodesList

We include togglefavaction, favorites, and store as props, and we destructure state, a dispatch from the store. In order to select our favorite episode, we include the toggleFavAction method in an onClick event, and pass the state, dispatch and episode props as arguments to the function.

Lastly, we loop through the favorite state to check if fav.id(favorite ID) matches the episode.id. If it does, we toggle between the Unfav and Fav text. This helps the user know if they have favorited that episode or not.

We are getting close to the end. But we still need a page where favorite episodes can be linked to when the user chooses among the episodes on the home page.

If you’ve gotten this far, give yourself a pat on the back.

Favpage Component

In the components folder, create a FavPage.tsx file. Copy and paste the following code to it:

import React, { lazy, Suspense } from 'react' import App from '../App' import { Store } from '../Store' import { IEpisodeProps } from '../types/interfaces' import { toggleFavAction } from '../Actions' const EpisodesList = lazy<any>(() => import('./EpisodesList')) export default function FavPage(): JSX.Element { const { state, dispatch } = React.useContext(Store) const props: IEpisodeProps = { episodes: state.favourites, store: { state, dispatch }, toggleFavAction, favourites: state.favourites } return ( <App> <Suspense fallback={<div>loading...</div>}> <div className='episode-layout'> <EpisodesList {...props} /> </div> </Suspense> </App> ) }

To create the logic behind choosing favorite episodes, we’ve written a little code. We import lazy and Suspense from React. We also import Store, IEpisodeProps, and toggleFavAction from their respective files.

We import our EpisodesList component using the React.lazy feature. Lastly, we return the App component. Inside it, we use the Suspense wrapper, and set a fallback to a div with the loading text.

This works similar to the Homepage component. This component will access the store to obtain the episodes the user has favorited. Then, the list of episodes gets passed to the EpisodesList component.

Let’s add a few more snippets to the HomePage.tsx file.

Include the toggleFavAction from ../Actions. Also include the toggleFavAction method as props.

import React, { useContext, useEffect, lazy, Suspense } from 'react' import App from '../App' import { Store } from '../Store' import { IEpisodeProps } from '../types/interfaces' import { fetchDataAction, toggleFavAction } from '../Actions' const EpisodesList = lazy<any>(() => import('./EpisodesList')) const HomePage = (): JSX.Element => { const { state, dispatch } = useContext(Store) useEffect(() => { state.episodes.length === 0 && fetchDataAction(dispatch) }) const props: IEpisodeProps = { episodes: state.episodes, store: { state, dispatch }, toggleFavAction, favourites: state.favourites } return ( <App> <Suspense fallback={<div>loading...</div>}> <section className='episode-layout'> <EpisodesList {...props} /> </section> </Suspense> </App> ) } export default HomePage

Our FavPage needs to be linked, so we need a link in our header in App.tsx. To achieve this, we use Reach Router, a library similar to React Router. William Le explains the differences between Reach Router and React Router.

In your CLI, run npm install @reach/router @types/reach__router. We are installing both the Reach Router library and reach-router types.

Upon successful installation, import Link from @reach/router.

import React, { useContext, Fragment } from 'react' import { Store } from './tsx' import { Link } from '@reach/router' const App = ({ children }: { children: JSX.Element }): JSX.Element => { const { state } = useContext(Store) return ( <Fragment> <header className='header'> <div> <h1>Money Heist</h1> <p>Pick your favourite episode</p> </div> <div> <Link to='/'>Home</Link> <Link to='/faves'>Favourite(s): {state.favourites.length}</Link> </div> </header> {children} </Fragment> ) } export default App

We destructure the store from useContext. Lastly, our home will have a Link and a path to /, while our favorite has a path to /faves.

{state.favourites.length} checks for the number of episodes in the favorites states and displays it.

Finally, in our index.tsx file, we import the FavPage and HomePage components, respectively, and wrap them in the Router.

Copy the highlighted code to the existing code:

import React from 'react' import ReactDOM from 'react-dom' import './index.css' import { StoreProvider } from './Store' import { Router, RouteComponentProps } from '@reach/router' import HomePage from './components/HomePage' import FavPage from './components/FavPage' const RouterPage = ( props: { pageComponent: JSX.Element } & RouteComponentProps ) => props.pageComponent ReactDOM.render( <StoreProvider> <Router> <RouterPage pageComponent={<HomePage />} path='/' /> <RouterPage pageComponent={<FavPage />} path='/faves' /> </Router> </StoreProvider>, document.getElementById('root') )

Now, let’s see how the implemented ADD_FAV works.

The “Add favorite” code works (Large preview) Remove Favorite Functionality

Finally, we will add the “Remove episode feature”, so that when the button is clicked, we toggle between adding or removing a favorite episode. We will display the number of episodes added or removed in the header.

STORE

To create the “Remove favorite episode” functionality, we will add another case in our store. So, go over to Store.tsx and add the highlighted code:

import React, { useReducer, createContext } from 'react' import { IState, IAction } from './types/interfaces' const initialState: IState = { episodes: [], favourites: [] } export const Store = createContext<IState | any>(initialState) const reducer = (state: IState, action: IAction): IState => { switch (action.type) { case 'FETCH_DATA': return { ...state, episodes: action.payload } case 'ADD_FAV': return { ...state, favourites: [...state.favourites, action.payload] } case 'REMOVE_FAV': return { ...state, favourites: action.payload } default: return state } } export const StoreProvider = ({ children }: JSX.ElementChildrenAttribute): JSX.Element => { const [state, dispatch] = useReducer(reducer, initialState) return {children} }

We add yet another case named REMOVE_FAV and return an object containing the copy of our initialState. Also, the favorites state contains the action payload.

ACTION

Copy the following highlighted code and paste it in action.ts:

import { IAction, IEpisode, IState, Dispatch } from './types/interfaces' export const fetchDataAction = async (dispatch: Dispatch) => { const URL = 'https://api.tvmaze.com/singlesearch/shows?q=la-casa-de-papel&embed=episodes' const data = await fetch(URL) const dataJSON = await data.json() return dispatch({ type: 'FETCH_DATA', payload: dataJSON.\_embedded.episodes }) } //Add IState withits type export const toggleFavAction = (state: IState, dispatch: any, episode: IEpisode | any): IAction => { const episodeInFav = state.favourites.includes(episode) let dispatchObj = { type: 'ADD_FAV', payload: episode } if (episodeInFav) { const favWithoutEpisode = state.favourites.filter( (fav: IEpisode) => fav.id !== episode.id ) dispatchObj = { type: 'REMOVE_FAV', payload: favWithoutEpisode } } return dispatch(dispatchObj) }

We import the IState interface from ./types/interfaces, because we’ll need to pass it as the type to the state props in the toggleFavAction function.

An episodeInFav variable is created to check if there’s an episode that exists in the favorites state.

We filter through the favorites state to check if a favorite ID doesn’t equal an episode ID. Thus, the dispatchObj is reassigned a type of REMOVE_FAV and a payload of favWithoutEpisode.

Let’s preview the result of our app.

Conclusion

In this article, we’ve seen how to set up TypeScript in a React project, and how to migrate a project from vanilla React to TypeScript.

We’ve also built an app with TypeScript and React to see how TypeScript is used in React projects. I trust you were able to learn a few things.

Please do share your feedback and experiences with TypeScript in the comments section below. I’d love to see what you come up with!

The supporting repository for this article is available on GitHub.

References
  1. How To Migrate A React App To TypeScript,” Joe Previte
  2. Why And How To Use TypeScript In Your React App?,” Mahesh Haldar
(ks, ra, il, al)
Categories: Web Design

How To Build A Vue Survey App Using Firebase Authentication And Database

Smashing Magazine - Fri, 05/08/2020 - 04:00
How To Build A Vue Survey App Using Firebase Authentication And Database How To Build A Vue Survey App Using Firebase Authentication And Database David Atanda 2020-05-08T11:00:00+00:00 2020-05-20T10:51:42+00:00

In this tutorial, you’ll be building a Survey App, where we’ll learn to validate our users form data, implement Authentication in Vue, and be able to receive survey data using Vue and Firebase (a BaaS platform).

As we build this app, we’ll be learning how to handle form validation for different kinds of data, including reaching out to the backend to check if an email is already taken, even before the user submits the form during sign up.

Also, the app would handle logging in of the user with restful APIs. It’ll make use of Authguard in Vue router to prevent users that are not logged in from getting access to the survey form, and successfully send the survey data of logged-in users to a secure database.

Just so we’re on the same page, let’s clarify what Firebase is, and what it’ll be doing in this tutorial. Firebase is a toolset to “build, improve, and grow your app”, it gives you access to a large portion of the services that developers would normally have to build themselves, but don’t really want to build, because they’d rather be focusing on the app experience itself. This includes things like analytics, authentication, databases, file storage, and the list goes on.

This is different than traditional app development, which typically involves writing both frontend and backend software. The frontend code just invokes API endpoints exposed by the backend, and the backend code actually does the work. However, with Firebase products, the traditional backend is bypassed, putting the work into the client. This technically allows front-end engineers like myself to build full-stack applications writing just front end code.

The bottom line is that Firebase would act as our backend in this project by providing us with the necessary API endpoints to handle both our authentication and database needs. In the end, you’ll have built a functional survey app using Vue+ Firebase. After that, you can go ahead and build any web app of your choice using these same processes, even with a custom backend.

To follow along, you need to have Node and npm/yarn installed on your machine. If you do not have that done already, follow these quick guides to install yarn or npm on your machine. You also need to have a basic understanding of Vue, Vuex and Vue router syntax for this tutorial.

The starter files for this tutorial are right here, which contains the base files for this project, and here is the repo for the completed demo. You can clone or download the repos and run npm install in your terminal.

After installing the starter file, you’ll see a welcome page, which has the options to sign up and sign in. After getting logged in you can then have access to the survey.

This describes how our survey app is going to be functioning. (Large preview)

Feel free to create a new project if you’ll like to build this project entirely on your own, just make sure to install Vuex, Vue router, Vuelidate and axios into your Vue project. So let’s jump right in:

First, we’ll need a Firebase account to set up this project which is very much like creating a container for our app, giving us access to the database, various means of authentication, hosting, etc. It’s straight forward to set up once you’re on the Firebase site.

The landing page where you can sign up and start your Firebase journey. (Large preview) Creating Firebase projects (Large preview)

Now that we have our project, the next thing is to set up both our authentication system and database (Realtime database) on Firebase.

  • Click on the “authentication” option;
  • Set up the “sign-in method” we want (in this case email/password).
Setup email/password Auth method for the project. (Large preview)
  • Click on “database”.
  • Choose “Realtime database” and copy this link that’s right on top.

It’ll be very useful as the API endpoint when we want to send the data to our firebase database.

We’ll refer to this API as the database API. To use it, you’ll have to add the name of the database of your choice when sending it. For example, to send to a database called user. You simply add user.json at the end:

{databaseAPI}/user.json Use the API above the database itself to send data to the database. (Large preview)

After this, we’ll then go to Firebase auth rest API documentation to get our sign up and sign in API endpoints. Within these endpoints, there will be a need for our project’s API key, which can be found in our project settings.

Validation

Back to our code, there’ll be a validation of the signup data before been sent to the server, just to make sure the user is sending appropriate information. We’ll be using Vuelidate which is a cool library that makes validation easier in Vue. First of all, install Vuelidate into the project:

npm i vuelidate

Go to src/components/auth/signup.vue and within the script tag import vuelidate and all the necessary events that we’ll need from the library as seen below.

Note: You can check the docs for a full overview of the library and all available events.

import { required, email, numeric, minValue, minLength, sameAs } from 'vuelidate/lib/validators'

A quick explanation:

required The value is compulsory email Value must be an email numeric Must be a number minValue Least numerical value the user can input. sameAs Used to compare between two values to make sure they’re the same

Also import axios to be able to send an HTTP request to the server:

import axios from 'axios'

Before we go on, we’ll need to add some rules to the database to be able to validate the email as we should, just as seen below:

The database rules help decide you can or cannot access the database at any point in time. (Large preview) "read" = "true"

Meaning that the database can be read without any hindrance from the client-side.

"write" = "auth" !== null

You can’t write on the database except you’re an authenticated user.

"Users" = { "onIndex" : ["email"] }

This allows us to query the users document with an index of email. That is, you can literally filter the database for a unique email.

Then add a custom computed property with the name validations just like we have methods, computed, etc.

Under validations we’ll have methods to validate the necessary data starting from email where it’s required and obviously must be an email. Also, we want to be able to tell a user when an email has already been taken by someone else, by checking the database after the user has typed it using something called async validators all within a custom validator and it’s all supported by vuelidate.

validations : { email: { required, email, unique: val => { if (val === '') return true return axios.get('https://vue-journal.firebaseio.com/users.json?orderBy="email"&equalTo="' + val + '"') .then(res => { return Object.keys(res.data).length === 0 }) } } }

Then under unique, query the database using axios and use the default Object.keys to return the response only if it’s length is 0.

For the age, you’ll add required, numeric, and a min value of 18 that’s assigned to minVal as its properties.

age: { required, numeric, minVal: minValue(18) }

Password’s properties are required, with a minimum length of 6 assigned to minLen.

password: { required, minLen: minLength(6) }

confirmPassword properties are basically to be the same as the password.

confirmPassword: { sameAs: sameAs(vm => { return vm.password }) }

To tell the user that the email is taken, use v-if to check if unique is true or false. If true, then it means that the returned Object’s length is 0, and email can still be used as well as vice versa.

In the same manner, you can check if the user input is an actual email using v-if.

And for all the surrounding divs on the individual input, we will add a class of invalid that becomes active once there’s an error on that input.

To bind the validation events to each of the input in the HTML, we use $touch() as seen with the email below.

<div class="input" :class="{invalid: $v.email.$error}"> <h6 v-if="!$v.email.email">Please provide a valid email address.</h6> <h6 v-if="!$v.email.unique">This email address has been taken.</h6> <input type="email" placeholder="Email" id="email" @blur="$v.email.$touch()" v-model="email"> </div>

Age, password, and confirmPassword will be binded to their HTML input in a similar manner as the email.

And we’ll make the ‘Submit’ button inactive if there’s an error in any of the input.

<button type="submit" :disabled="$v.$invalid">create</button>

Here’s a complete CodePen example for this vuelidate section.

Vuelidate is used here to determine the kind of data been sent to the database. (Large preview) Authentication

This app is an SPA and doesn’t reload like traditional sites, so we’ll be using Vuex, as our single “source of truth” to allow every component in our app to be aware of the general authentication status. We go to our store file, and create both sign-in/sign-up method within actions.

The response (token and userId) received when we send the users data, are going to be stored within our state. This is important because the token is going to be used to know if we’re still logged in or not at any point within our app.

The token, userId, and user are created in the state with an initial value of null. We’ll get to the user much later, but for now, we’ll focus on the first two.

state: { idToken: null, userId: null, user: null }

Mutations are then created to change the state when needed.

authUser Saves the token and userId storeUser Stores the user info clearAuthData Erases the data back to the initial state mutations: { authUser (state, userData) { state.idToken = userData.token state.userId = userData.userId }, storeUser (state, user) { state.user = user }, clearAuthData (state) { state.idToken = null state.userId = null state.user = null } }

For sign-up/sign-in, we’ll have to create individual actions for both, where we send our auth requests to the server. After which our response(token and userId) from sign-up/sign-in is committed to authUser, and saved on the local storage.

signup ({commit, dispatch}, authData) { axios.post('https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyCFr-OMMzDGp4Mmr0t66w2cTGfNazYjptQ', { email: authData.email, password: authData.password, returnSecureToken: true }) .then(res => { console.log(res) commit('authUser', { token: res.data.idToken, userId: res.data.localId }) localStorage.setItem('token', res.data.idToken) localStorage.setItem('userId', res.data.localId) localStorage.setItem('email', res.data.email) dispatch('storeUser', authData) setTimeout(function () { router.push('/dashboard') }, 3000) }) .catch(error => console.log(error)) } login ({commit}, authData) { axios.post('https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=AIzaSyCFr-OMMzDGp4Mmr0t66w2cTGfNazYjptQ', { email: authData.email, password: authData.password, returnSecureToken: true }) .then(res => { console.log(res) localStorage.setItem('token', res.data.idToken) localStorage.setItem('userId', res.data.localId) localStorage.setItem('email', res.data.email) commit('authUser', { token: res.data.idToken, userId: res.data.localId }) router.push('/dashboard') }) .catch(error => console.log(error.message)) }

But here’s the tricky part, what we’ll do with the sign-up action particularly is to send only the email and password to be registered in the authentication database. In the real sense, we don’t have access to use the data in this authentication database, and we did not send any of our sign-up data besides email/password.

So what we’ll do is to create another action to send the complete sign-up data to another database. In this separate database document, we’ll have complete access to all the information we choose to save there. We’ll call this new action is called storeUser

We then go to our sign-up action and dispatch the entire object containing our sign-up data to a database we now have access to through storeUser.

Note: You might not want to send your user’s password with storeUser to the database for security reasons.

storeUser ({ state}, userData) { if (!state.idToken) { return } axios.post('https://vue-journal.firebaseio.com/users.json' + '?auth=' + state.idToken, userData) .then(res => console.log(res)) .catch(error => console.log(error)) } }

storeUser adds a query using our newly gotten token and database API while posting to the database.

This is because we cannot write to our database, except we’re authenticated with our proof( the token). That’s the rule we gave Firebase at the beginning, remember?

“write” = “auth” !== null

The complete code for sign-up/sign-in actions are right here.

Then dispatch both the sign-up and sign-in from their components within the onSubmit method to the respective actions in the store.

methods : { onSubmit () { const signupData = { email : this.email, name : this.name, age : this.age, password : this.password, confirmPassword : this.co nfirmPassword } this.$store.dispatch('signup', signupData) } } }

Note: signupData contains the form’s data.

methods : { onSubmit = { const formData = { email : this.email, password : this.password } this.$store.dispatch('login', {email: formData.email, password: formData.password}) } } AuthGuard

There’s a need for AuthGuard to prevent users that are not logged in from getting access to the dashboard where they’ll send the survey.

Go to the route file and import our store.

import store from './store'

Within the route, go to the dashboard’s path and add the following:

const routes = [ { path: '/', component: WelcomePage }, { path: '/signup', component: SignupPage }, { path: '/signin', component: SigninPage }, { path: '/dashboard', component: DashboardPage, beforeEnter (to, from, next) { if (store.state.idToken) { next() } else { next('/signin') } } } ]

All this does is to check whether there’s a token in the state, if yes, we give access to the dashboard and vice versa.

LogOut

To create our logout option we’ll make use of clearAuth that we created earlier under mutations which just sets both the token and userId to null.

We now create a new logout action , that commits to clearAuth, delete local storage and add router.replace('/') to redirect the user completely.

actions: { logout ({commit}) { commit('clearAuth') localStorage.removeItem('token') localStorage.removeItem('userId') router.replace('/') } }

In the header component, we have an onLogout method which dispatches our logout action in the store.

methods: { onLogout() { this.$store.dispatch('logout') } }

We then add a @click to the button which fires the onLogout method as we can see here.

<ul @click="onLogout">Log Out</ul> UI_State

Now that we’ve given conditional access to the dashboard, the next step is to remove it from the nav bar, so only authenticated users can view it. To do that, we would add a new method under the getters called ifAuthenticated which checks if the token within our state is null. When there’s a token, it shows that that the user is authenticated and we want them to see the survey dashboard option on the nav bar.

getters: { isAuthenticated (state) { return state.idToken !== null } }

After which, you go back to the header component and create a method auth under computed, which dispatches to our isAuthenticated within the getters we’ve just created in the store. What this does is that isAuthenticated would return false if there’s no token, which means auth would also be null and vice versa.

computed: { auth () { return this.$store.getters.ifAuthenticated } }

After this, we add a v-if to our HTML to check if auth is null or not, determining whether that option would show on the nav bar.

<li v-if='auth'> <router-link to="/dashboard">Dashboard</router-link> </li> <li v-if='!auth'> <router-link to="/signup">Register</router-link> </li> <li v-if='!auth'> <router-link to="/signin">Log In</router-link> </li>
  • You’ll find the complete code of the UI State section here.
There’s change in the header based on the authentication status of the user. (Large preview) AutoLogin

When we reload our app we lose the data and are signed out, having to start all over. This is because our token and Id are stored in Vuex, which is javascript, and this means that our app gets reloaded with the browser when refreshed.

And so finally, what we’ll be doing is to retrieve the token within our local storage. By so doing, we can have the user’s token on the browser regardless of when we refresh the window, and have a method auto log-in our user in as much as the token is still valid.

A new actions method called AutoLogin is created, where we’ll get the token and userId from the local storage, and commit our data to the authUser method in the mutations.

actions : { AutoLogin ({commit}) { const token = localStorage.getItem('token') if (!token) { return } const userId = localStorage.getItem('userId') const token = localStorage.getItem('token') commit('authUser', { idToken: token, userId: userId }) } }

We then go to our App.vue and write a created method, that’ll dispatch the autoLogin from our store every time the app is loaded.

created () { this.$store.dispatch('AutoLogin') } Fetch_User_Data

We want to welcome the user on the dashboard by displaying the user’s name. And so, another action called fetchUser is created which first checks if there’s a token as usual. Then, it goes on to get the email from local storage and queries the database as done earlier with the email validation.

This returns an object containing the user’s data initially submitted during sign-up. We then convert this object into an array and commit it to the storeUser mutation initially created.

fetchUser ({ commit, state}) { if (!state.idToken) { return } const email = localStorage.getItem('email') axios.get('https://vue-journal.firebaseio.com/users.json?orderBy="email"&equalTo="' + email + '"') .then(res => { console.log(res) // const users = [] console.log(res.data) const data = res.data const users = [] for (let key in data) { const user = data[key] user.id = key users.push(user) console.log(users) } commit('storeUser', users[0]) }) .catch(error => console.log(error)) }

After which we create another getter called user which returns the state.user already committed through storeUser.

getters: { user (state) { return state.user }, isAuthenticated (state) { return state.idToken !== null } }

Back to the dashboard, we create a new computed method called name that returns state.user.name only if the user exists.

computed: { name () { return !this.$store.getters.user ? false : this.$store.getters.user.name } }, created () { this.$store.dispatch('fetchUser') } }

And we’ll also add the created computed property to dispatch the fetchUser action once the page is loaded. We then use the v-if in our HTML in order to display the name if the name exists.

<p v-if="name">Welcome, {{ name }} </p> Send_Survey

To send the survey, we’ll create a postData action that sends the data to the database using the database API, with the token to show the server that the user is logged in.

postData ({state}, surveyData) { if (!state.idToken) { return } axios.post('https://vue-journal.firebaseio.com/survey.json' + '?auth=' + state.idToken , surveyData) .then(res => { console.log(res) }) .catch(error => console.log(error)) }

We come back to the dashboard component and dispatch the data to our postData action in the store.

methods : { onSubmit () { const postData = { price: this.price, long: this.long, comment: this.comment } console.log(postData) this.$store.dispatch('postData', postData) } }

There we have it, we’ve got a lot of useful features implemented into our demo application while communicating with our Firebase server. Hopefully, you’ll be using these powerful features in your next project as they’re very critical to building modern web apps today.

If you have any questions, you can leave them in the comments section and I’ll be happy to answer every single one of them!

  • The demo for the tutorial is live here.
The completed survey app (Large preview)

Other resources that may prove useful includes:

  • To understand more about Firebase and the other services it offers, check out Chris Esplin’s article, “What Is Firebase?
  • Vuelidate is a really nice library you should really dig into. You should read through its documentation to gain full insight.https://vuelidate.js.org/.
  • You can also explore axios on its own, especially if you want to use it in bigger projects.
(ra, yk, il)
Categories: Web Design

9 Best Device Mockups for Your Web and Mobile App

What are the main graphical elements of a modern presentation? If you think it is beautiful fonts or stocks taken from the big online image retailers, then you are...

The post 9 Best Device Mockups for Your Web and Mobile App appeared first on Onextrapixel.

Categories: Web Design

Reducing Design Risk

Smashing Magazine - Thu, 05/07/2020 - 03:30
Reducing Design Risk Reducing Design Risk Eric Olive 2020-05-07T10:30:00+00:00 2020-05-20T10:51:42+00:00

Lean, agile, do more with less. Again, and again, design culture urges us to move quickly and trim research and design operations to the point where design becomes a mere thread in the larger corporate spool.

Author and designer Nikki Anderson explains the consequences of this pressure to conduct research at lightning speed:

“When we’re asked to synthesize at the speed of light, user research becomes a way for teams to take a shortcut — to invent assumptions based on quickly made correlations, opinions, and quotes.”

The result is design based on assumptions or incomplete information about users and customers. For example, a Fortune 500 company (let’s call it Company Q) hired me to conduct a usability test for a complex user interface (usability testing involves a series of one-on-one sessions with real users who are asked to complete specific tasks while using a product or piece of software).

The test yielded what would likely become recognizable patterns, and I was halfway through the analysis when I was ordered to pause and send the client the findings immediately. My explanation about the need for more time to conduct a thorough and nuanced analysis fell on deaf ears:

“Just send a short video.”

I reluctantly sent a video snippet showing a participant struggling with the user interface (UI).

Biased design decision based on observation of a single usability test participant. (Large preview)

There was no time for background, context, or nuance. The product manager at Company Q recognized the participant in the video from a previous encounter and dismissed his struggles: “He’s a crank, we can’t base decisions on him.”

The company moved forward without addressing this serious UI issue.

This product manager had become emotionally attached to his product (see endowment effect below). This emotional attachment hindered his ability to assess the product’s strengths and weaknesses objectively. It’s not surprising that professionals develop strong feelings about their products.

Understandable, but also problematic. As UX guru Jared Spool explains in an article about the ROI of UX, dismissing user needs carries a high cost:

For example, say you get many support calls because the design doesn’t do something the users expect. That’s a high cost due to a poor design decision.

How costly? According to Jeffrey Rumburg of HDI, the average cost of a single support call in North America is $15.56. Even if support calls only increase by 83,000 each month, the annual cost is over $15 million.

In contrast, addressing design problems works. According to the McKinsey report, “The Business Value of Design”: “One online gaming company discovered that a small increase in the usability of its home page was followed by a dramatic 25 percent increase in sales.”

Note: For this study, McKinsey tracked the design practices of 300 publicly listed companies over a five-year period in multiple countries and industries. Their senior business and design leaders were interviewed or surveyed. The McKinsey team collected more than two million pieces of financial data and recorded more than 100,000 design actions.

These numbers demonstrate the direct financial costs associated with rushing market research and shortchanging user and customer concerns. They also illustrate the financial benefit of addressing customer concerns.

In this article, I’ll shed light on the techniques for addressing these concerns:

  1. Carefully selecting a research location;
  2. Compromising with stakeholders to allow sufficient time for analysis without delaying the design process;
  3. Making sound, evidence-based design decisions;
  4. Engaging in design reduction.
1. Context Over Convenience: Why Location Matters

Where you conduct research matters as much as the research method. Before booking a facility for your next user interview, consider the importance of location. You might not want to book a quiet meeting room if users work in a noisy environment with numerous distractions. In fact, the user’s environment will help you identify the best research method for gathering insights (interviews, diary studies, observation/contextual inquiry, usability tests, cognitive walkthroughs, etc.).

This is precisely what happened when our team conducted UX research for a manufacturer of large construction equipment. We could have brought machine operators to a quiet showroom to ask them questions about the equipment and what did and did not work well.

This would have been the easy but incorrect choice. Instead, we traveled to construction sites in the U.S., Mexico, and Colombia where we observed operators using the equipment outside where it was dusty, dirty, and loud.

Construction Site in Colombia. (Large preview)

On-the-ground observations included:

  • Risks of vehicle collisions due to noise and low visibility when winds were high.
  • The difficulty shorter operators encountered when reaching for certain controls in the cab (operators in Latin America were, on average, smaller than their U.S. counterparts).
  • The rapid corrosion of metal equipment caused by salt on a construction site near the ocean.

Observing users in their real-world work environment:

  • Reduced the risk of solving the wrong problem because we did not rely on second-hand information from sales or product (this happens more often than you might think).
  • Allowed us (the researchers) to hear the noise, see the dust, and feel the bumps while riding on these enormous machines.
  • Provided actionable insights that could not have been gathered in an office.
The author interviewing a machine operator in Colombia. (Large preview)

Our research at sites in Mexico and Colombia demonstrated the truth of the old adage. Meeting users where they worked every day yielded rich, qualitative data that our client used to inform important design decisions.

2. Compromise

This was a good outcome. The fieldwork in Mexico and Colombia identified real-world problems, and stakeholders acted on this information.

This is not always the case. There is a temptation to make design decisions quickly based on incomplete information as happened to Walmart when management decided to change aisle and shelving design based on a customer survey. When customers were asked if stores were too cluttered, they said yes. Walmart spent millions re-designing stores only to lose more than $1 billion in revenue. When Walmart reverted to the cluttered aisles, sales increased. What happened?

Two reasons for this fiasco were likely a poorly worded survey and incomplete analysis. Walmart relied too heavily on what customers said rather than what they did. The importance of placing considerable weight on what users and customers do is a bedrock principle in customer and user experience.

“Rather than just ask shoppers what they think they would like, I can follow someone through their shopping trip in a grocery or mass merchandise store like Walmart and Sam’s Club and then interview them as they load their bags into the car. What is striking is the wide gap between what they say they did, and what I observed.”

— Paco Underhill, author of Why We Buy. New York Times Article about Walmart.

Underhill, a legend in consumer and market research, is exactly right. Unfortunately, even when stakeholders agree to fund observation (ride-alongs, shop-alongs, contextual inquiry), there is considerable pressure to move forward the moment a UX or market study is done leaving little time for thorough analysis.

The goal in these situations is to strike a balance between speed and thoroughness. Product managers and other stakeholders have a great deal of responsibility and are often under pressure to move products to market quickly. Rushing the design process, however, can result in overlooking key user needs emerging from research.

Analysis. (Image by StartupStockPhotos from Pixabay) (Large preview) Preliminary Design Work. (Photo by Syda Productions from Depositphotos) (Large preview)

Compromise during the transition from research analysis to design serves two purposes. First, it allows researchers sufficient time to review, reflect, and report accurate and actionable findings that will help the design team move forward. Second, as with any endeavor, a willingness to compromise establishes a degree of trust.

3. Better Design Decisions

Compromise and trust are a sound basis for establishing a constructive relationship between researchers, designers, and stakeholders. Such relationships contribute to an environment conducive to better design decisions. These points seem straightforward, even obvious.

Straightforward perhaps but not easily achieved. Why? Human nature. Humans are subject to what psychologists call the endowment effect, the tendency to overvalue objects you own simply because they belong to you. Selling a house is a classic example. As the homeowner, you are emotionally attached to your house because you’ve put effort into maintenance and improvements. The house holds fond memories. After all, you live there. None of this matters to the buyer. She only cares about the objective market value and getting the best house for the least amount of money.

Endowment Effect: Emotional attachment leads to an inflated sense of value. (Image by Pexels from Pixabay) (Large preview)

Once the endowment effect takes hold, it’s difficult for people to part with the object, a house in this example. In the context of design, changing a UI or physical product is roughly equivalent to parting with it.

For example, while evaluating a complex UI for a programmable logic controller, the product manager announced to me and a room full of stakeholders: “My name is Jim, and I love this product.” Points for honesty. As expected, when I delivered the report, Jim held firmly to his belief that the UI was fine and did not require modification. He was, understandably, attached to the machine and the UI. Unfortunately, the company’s customers did not share this attachment as illustrated by ongoing customer complaints.

The data supports this conclusion. According to the McKinsey report mentioned above: “Less than 5 percent of those we surveyed reported that their leaders could make objective design decisions.”

The endowment effect is one of many barriers to making sound design decisions. See A Designer’s Guide To Better Decisions to learn how to avoid other, common decision traps.

Awareness of the endowment effect and other decision traps contributes to better design because it allows us to make tough choices during the actual design process.

4. Design Reduction

One such choice is what to remove from an existing design or an early design iteration. For example, the image shown below left could easily be an early iteration of a mobile app.

Cluttered Layout: Fake Fitness App. (Large preview) Cleaner Layout: Fake Fitness App. (Large preview)

Few will argue against the power of simple, elegant, and engaging design. Such successes are often the result of careful, thoughtful reduction. From the number and size of elements on the screen to the simplicity or complexity of the color palette, it all comes down to reducing the design to the point that it’s clean and easy to use without removing anything essential.

Even in the cleaner example (above right), a designer might ask if “This Month” and “165: Max Pulse” are necessary. If not, removing them would be yet another reduction.

The point is not to debate the UI details for this fake fitness app. Rather, designers must anticipate the “everything-but-the-kitchen-sink” effect and make the case for removing unnecessary design elements. Effective techniques include:

  • Gently reminding stakeholders and other team members about the risks of a heavy cognitive load.
  • Sharing cluttered designs (any app or site will do) with the team and asking them to quickly locate a specific feature. Their struggle to find the feature will make the point.
  • Sharing video clips of past research projects for your company showing how easily users become confused when interacting with a crowded UI.

Adhering to this reduction technique early in the design process benefits the business by decreasing the chance of user confusion, task or cart abandonment, and unhappy customers.

Design reduction is essential to creating engaging, user-centered design but only works when coupled with rigorous user research that contributes to informed design decisions.

Conclusion

Because research, decisions, and the design process go together, the focus of this article has been to identify the risks of rushing user research and design. Mitigating this risk does not require doubling the size of research and design teams. Instead, we’ve proposed four practical techniques that teams can implement immediately:

  • Context over convenience
    Location matters. Whether at home, a café, or on a noisy construction site, conduct UX and market research where users will be when interacting with your product.
  • Compromise
    When business stakeholders cannot simply wait for a thorough analysis, compromise. At the stakeholder’s direction, the design team can move forward with limited design changes while agreeing not to make major changes until the final research analysis is complete.
  • Better design decisions
    Make better decisions by keeping an eye out for the all-too-human tendency to become attached to a design you have created.
  • Reduction
    Remove unnecessary UI elements leaving only what is necessary for users and customers to complete the task at hand.
(ah, yk, il)
Categories: Web Design

Pages

1 2 3 4 5 6 7 8 9 next › last »