Archive

Archive for August, 2018

Popular Design News of the Week: August 13, 2018 – August 19, 2018

August 19th, 2018 No comments

Every week users submit a lot of interesting stuff on our sister site Webdesigner News, highlighting great content from around the web that can be of interest to web designers.

The best way to keep track of all the great stories and news being posted is simply to check out the Webdesigner News site, however, in case you missed some here’s a quick and useful compilation of the most popular designer news that we curated from the past week.

Note that this is only a very small selection of the links that were posted, so don’t miss out and subscribe to our newsletter and follow the site daily for all the news.

Scroll Bouncing on your Websites

Site Design: Kommigraphics

How Ikea Quietly Tweaks its Design Around the World

Screenlife App – A UI/UX Case Study

Reviewed: New Logo and Identity for Evernote

Fairtrade Website Redesign – A UX Case Study

Why Designers Don’t Want to Think When They Read

A Small Tool to Help You Generate Color Scales in an Instant

Font Flipper — Tinder for Google Fonts

How to Choose a Name for a New Product (with Minimal Stress)

Neede – An Online Design Resource Library

You Can’t Research Without Context

Tini.Es

Study: Blue Light from Screens Can Steadily Blind Us

How to Create a Customer Journey Map [step by Step]

The Design is the Implementation

CanSnippet CE – A CMS for Sharing Code

10,000 Original Copies

HoverSignal – Increase your Website’s Conversions with Notifications

100 Days of Motion Design

Being a Great Designer is About More than Being Great at Design

A Beginner’s Guide to Aspect Ratio

Are Gutenberg’s Bad Reviews a Sign of Failure?

Using Micro-interactions to Enhance Search

How to Launch a Side Project in 10 Days

Want more? No problem! Keep track of top design news from around the web with Webdesigner News.

Add Realistic Chalk and Sketch Lettering Effects with Sketch’it – only $5!

Source

Categories: Designing, Others Tags:

Firefox Multi-Account Containers

August 17th, 2018 No comments

It’s an extension:

Each Container stores cookies separately, so you can log into the same site with different accounts and online trackers can’t easily connect the browsing.

A great idea for a feature if you ask me. For example, I have two Buffer accounts and my solution is to use different browsers entirely to stay logged into both of them. I know plenty of folks that prefer the browser version of apps like Notion, Front, and Twitter, and it’s cool to have a way to log into the same site with multiple accounts if you need to — and without weird trickery.

This is browsers competing on UI/UX features rather than web platform features, which is a good thing. Relevant: Opera Neon and Refresh.

Direct Link to ArticlePermalink

The post Firefox Multi-Account Containers appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

The Fascinating History of the Apple Logo

August 17th, 2018 No comments
Apple Logo

Have you ever wondered what do a bitten apple and technology have in common? The Apple logo has become one of the most iconic and world-wide known logo, but not many people know the history and the meaning of the bitten apple.

The first logo of the company doesn’t look at all like the actual one that represents the Apple brand. The first image of the company has only survived for one year, before Steve Jobs asked the talented artist Rob Janoff to create something more modern and representative for Apple. The finial logo, designed by Ronald Wayne and Steve Jobs, illustrated Sir Isaac Newton under an apple tree, and as background it had a poem written on the side of the drawing. The quotation by Wordsworth that was also inscribed into the logo said: “Newton… a mind forever voyaging through strange seas of thought.”

The Apple Logo: How did it become an iconic image of the company?

The iconic Apple logo, the bitten apple that we can now find it on all the company’s products, was created by Rob Janoff in the 70’s. According to him, the reason Steve Jobs wanted a bitten apple was that people would be able to tell apart the apple from a tomato. You can also look at the bite as a clever play on word. Instead of spelling it B-I-T-E, you can spell it B-Y-T-E as in the measurement for digital storage. It is, of course, a strong reference for a tech company.

The rainbow Apple Logo

The first version the bitten logo was a rainbow stripped apple. This Apple logo represented the company between 1976 and 1998. Rob Janoff explains why Jobs opted for the rainbow in one of his interviews. Once the personal computer Apple II was launched, it was the first computer ever that could display colors on the screen. The representatives of the company wanted to make this fact known by all. Also, the colors were also an attempt to make the logo more accessible, and to attract the young generation.

In 1998, things started to change again, as well as the Apple company’s logo. Steve jobs decided to change it into a monochromatic apple. The rainbow colors of the apple were going to go out of fashion. The new monochromatic logo matched the image of the newest products on the market better than anything else.

Regarding the name of the company, there are many speculations. Unfortunately, there isn’t one most plausible theory among all the existent ones. Some believe that the founders Steve Jobs and Steve Wozniak wanted their start up to appear on the first pages of the phone books. Others believe that they wanted to stand out of the crowd with a simple name, easy to be remembered by. They wanted to create a contrast between their company and all the other hard to remember names of tech companies such as TRS-80, IBM, or Cincom. Also, the idea that the founders wanted to bring a tribute to The Beatles’ record label.

Apple Logo

Read More at The Fascinating History of the Apple Logo

Categories: Designing, Others Tags:

10 WordPress tools & services you need to try (You’re welcome!)

August 17th, 2018 No comments

The WordPress design team set out to build the ultimate website-building platform. That time, they had several things in mind. Among them, they wanted to make building websites as easy as possible. Also, they planned to allow web designers to build exactly what they want down to the finest detail. Users can do so without having to work around restrictions.

It’s an obvious fact that not only did they succeed, they also empowered a lot of web designers. With each new tool or service, web designers are able to build advanced websites.

Take a few minutes to go down this list of 10 top WordPress tools and services. Chances are, you’ll come across a product or service you’ll wish you had to work with a long time ago.

  1. Elementor Page Builder

If you are looking for a powerful web design solution that is also open source and based on WordPress, Elementor is your best choice. With Elementor, you can reach the most astounding results that professional web designers charge a fortune for. It solves most of the limitations imposed on users by the various WordPress themes.

Elementor, with its visual frontend page builder, is the genuine article if you’re looking for a product that enables you to build anything you want down to the minutest of details, without having to write a single line of code. Better yet, this open source page builder is super-fast, it works with any template. Did we mention it costs you nothing to get started?

With Elementor, you can start a page from scratch, use any of its 130+ templates, use your own, or download one from another source.

Elementor’s ranking as the #1 WordPress page builder is entirely justifiable in terms of performance, capabilities, and popularity. With respect to the latter, its user base has grown from a mere handful a little less than 2 years ago to over 1 million users today.

  1. Brizy

Two of Brizy’s top assets are its ease of use and the UX it provides. An additional top asset would have to be that it is free to download and use by anyone having a WordPress website.

Brizy has managed the seemingly impossible in that it provides users with an impressive number of website-building features and options while at the same time presenting them with a user interface that is remarkably free of clutter and distractions. If you need a particular function, setting, or option it’s there when you need it. You don’t have to conduct a search among a host of sidebar items for each and every action you take.

The best way to introduce yourself to Brizy is to test it on their website. The HTML you generate is free and yours to keep and to use however you wish.

  1. Posts Table Pro WordPress Table Plugin

The Posts Table Pro plugin is one you’ll wish you had long ago if your website efforts have included building tabular listings of posts and pages, document libraries, member directories, and the like. This dynamic plugin would have saved you many hours of data entry, which like most manual processes can often be somewhat error-prone.

Now, you can perform the same tasks quickly, error-free, and with the flexibility you need to create tables that exactly meet your requirements. With Posts Table Pro, you can select the pages, posts, custom post types or multimedia items you want to tabulate, order and sort them as you wish, and adjust column parameters, load times, and other characteristics as you deem necessary. Maybe it’s time to start using a tool that lets you build tables your way and do so with relative ease.

Posts Table Pro works with any WordPress theme and comes with expert support from the plugin developers.

  1. WordXpress

Unless you have a very small and simple website to maintain, you might be unaware of the time you spend performing edits and updates, eliminating malware, optimizing plugins, and performing backups. How much is your time worth? Would it be better spent building your business?

The WordXpress team of WordPress maintenance experts will do all of these for you. They will save you time and effort and relieve you of a ton of unnecessary stress, just as they’ve been doing for other website owners for the past decade.

  1. Logic Hop – Personalized Marketing for WordPress

Personalized marketing makes websites much more effective, and Logic Hop is the personalized marketing solution that can help you acquire more leads and generate more sales and conversions than generic marketing solutions are generally capable of. Personalized call-to-actions, for example, convert twice as well as the generic alternatives.

Logic Hop integrates with the tools you’re already using – like Google Analytics – or can collect its own data. All this opens up your WordPress site for personalized marketing and a more effective website.

  1. Goodie

Goodie appeals to small businesses who wish to have their design ideas directly converted into working code without having to go through a middleman. Goodie’s team of experienced developers can completely code your website design for $999. Whether you submit your design in digital file format or sketched out on paper, they’ll work with you to give you precisely the website you want.

  1. Starfish Reviews

Starfish Reviews is a plugin that works with any of the common online reviews platforms to enable you to encourage customer and follower reviews of your business. Having more 5-star reviews on Facebook, iTunes, Google, TripAdvisor, etc. can significantly increase sales since consumers look at and trust online reviews when buying. Ratings also has a positive effect on SEO.

Starfish Reviews sees that positive reviews get published and routes negative reviews back to you as feedback.

  1. Fixmysite.com

Here’s your opportunity to make Fixmysite.com your trusted neighborhood website garage. The Fixmysite.com web mechanics will fix on demand whatever is ailing your website to your complete satisfaction or give you your money back.

The Fixmysite.com team can also help you with web migration, speed optimization, malware removal issues, and provide installation services and perform site audits.

  1. WP Review Pro

Some review styles work better for a given type of product or service than others. WP Review Pro gives you the options

of summarizing reviews as approval percentages, stars ratings, ratios, and thumbs up and down depending upon what has been reviewed. This WooCommerce compatible best review plugin also enables you to generate product and service comparison tables.

  1. WordLift

WordLift is an open source software tool for bloggers, journalists, content marketers, SEO specialists, and web designers. It allows artificial intelligence work for you by translating your website’s articles and pages into machine-friendly content that search crawlers and personal digital assistants use to serve users the right information and help them take action.

This results in a richer and more engaging website UX and a growth of organic traffic.

Conclusion

Have you been looking for ways to build a better website? Or, maybe you’d like to improve a website’s performance, or extend its capabilities? Anyway, there’s something here for you.

More than a few of these tools enable you to add functionality to your websites. It would cost you an arm and a leg to have someone do it for you. Each of these top WordPress products and services is worth is worth its weight in gold.

Read More at 10 WordPress tools & services you need to try (You’re welcome!)

Categories: Designing, Others Tags:

Seriously, though. What is a progressive web app?

August 17th, 2018 No comments

Amberley Romo read a ton about PWAs in order to form her own solid understanding.

“Progressive web app” (PWA) is both a general term for a new philosophy toward building websites and a specific term with an established set of three explicit, testable, baseline requirements.

As a general term, the PWA approach is characterized by striving to satisfy the following set of attributes:

  1. Responsive
  2. Connectivity independent
  3. App-like-interactions
  4. Fresh
  5. Safe
  6. Discoverable
  7. Re-engageable
  8. Installable
  9. Linkable

Direct Link to ArticlePermalink

The post Seriously, though. What is a progressive web app? appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

Level up your .filter game

August 17th, 2018 No comments

.filter is a built-in array iteration method that accepts a predicate which is called against each of its values, and returns a subset of all values that return a truthy value.

That is a lot to unpack in one statement! Let’s take a look at that statement piece-by-piece.

  • “Built-in” simply means that it is part of the language—you don’t need to add any libraries to get access to this functionality.
  • “Iteration methods” accept a function that are run against each item of the array. Both .map and .reduce are other examples of iteration methods.
  • A “predicate” is a function that returns a boolean.
  • A “truthy value” is any value that evaluates to true when coerced to a boolean. Almost all values are truthy, with the exceptions of: undefined, null, false, 0, NaN, or "" (empty string).

To see .filter in action, let’s take a look at this array of restaurants.

const restaurants = [
    {
        name: "Dan's Hamburgers",
        price: 'Cheap',
        cuisine: 'Burger',
    },
    {
        name: "Austin's Pizza",
        price: 'Cheap',
        cuisine: 'Pizza',
    },
    {
        name: "Via 313",
        price: 'Moderate',
        cuisine: 'Pizza',
    },
    {
        name: "Bufalina",
        price: 'Expensive',
        cuisine: 'Pizza',
    },
    {
        name: "P. Terry's",
        price: 'Cheap',
        cuisine: 'Burger',
    },
    {
        name: "Hopdoddy",
        price: 'Expensive',
        cuisine: 'Burger',
    },
    {
        name: "Whataburger",
        price: 'Moderate',
        cuisine: 'Burger',
    },
    {
        name: "Chuy's",
        cuisine: 'Tex-Mex',
        price: 'Moderate',
    },
    {
        name: "Taquerias Arandina",
        cuisine: 'Tex-Mex',
        price: 'Cheap',
    },
    {
        name: "El Alma",
        cuisine: 'Tex-Mex',
        price: 'Expensive',
    },
    {
        name: "Maudie's",
        cuisine: 'Tex-Mex',
        price: 'Moderate',
    },
];

That’s a lot of information. I’m currently in the mood for a burger, so let’s filter that array down a bit.

const isBurger = ({cuisine}) => cuisine === 'burger';
const burgerJoints = restaurants.filter(isBurger);

isBurger is the predicate, and burgerJoints is a new array which is a subset of restaurants. It is important to note that restaurants remained unchanged from the .filter.

Here is a simple example of two lists being rendered—one of the original restaurants array, and one of the filtered burgerJoints array.

See the Pen .filter – isBurger by Adam Giese (@AdamGiese) on CodePen.

Negating Predicates

For every predicate there is an equal and opposite negated predicate.

A predicate is a function that returns a boolean. Since there are only two possible boolean values, that means it is easy to “flip” the value of a predicate.

A few hours have passed since I’ve eaten my burger, and now I’m hungry again. This time, I want to filter out burgers to try something new. One option is to write a new isNotBurger predicate from scratch.

const isBurger = ({cuisine}) => cuisine === 'burger';
const isNotBurger = ({cuisine}) => cuisine !== 'burger';

However, look at the amount of similarities between the two predicates. This is not very DRY code. Another option is to call the isBurger predicate and flip the result.

const isBurger = ({cuisine}) => cuisine === 'burger';
const isNotBurger = ({cuisine}) => !isBurger(cuisine);

This is better! If the definition of a burger changes, you will only need to change the logic in one place. However, what if we have a number of predicates that we’d like to negate? Since this is something that we’d likely want to do often, it may be a good idea to write a negate function.

const negate = predicate => function() {
  return !predicate.apply(null, arguments);
}

const isBurger = ({cuisine}) => cuisine === 'burger';
const isNotBurger = negate(isBurger);

const isPizza = ({cuisine}) => cuisine === 'pizza';
const isNotPizza = negate(isPizza);

You may have some questions.

What is .apply?

MDN:

apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

What is arguments?

MDN:

The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function’s arguments within the function by using the arguments object.

Why return an old-school function instead of a newer, cooler arrow function?

In this case, returning a traditional function is necessary because the arguments object is only available on traditional functions.

Returning Predicates

As we saw with our negate function, it is easy for a function to return a new function in JavaScript. This can be useful for writing “predicate creators.” For example, let’s look back at our isBurger and isPizza predicates.

const isBurger = ({cuisine}) => cuisine === 'burger';
const isPizza  = ({cuisine}) => cuisine === 'pizza';

These two predicates share the same logic; they only differ in comparisons. So, we can wrap the shared logic in an isCuisine function.

const isCuisine = comparison => ({cuisine}) => cuisine === comparison;
const isBurger  = isCuisine('burger');
const isPizza   = isCuisine('pizza');

This is great! Now, what if we want to start checking the price?

const isPrice = comparison => ({price}) => price === comparison;
const isCheap = isPrice('cheap');
const isExpensive = isPrice('expensive');

Now the isCheap and isExpensive are DRY, and isPizza and isBurger are DRY—but isPrice and isCuisine share their logic! Luckily, there are no rules for how many functions deep you can return.

const isKeyEqualToValue = key => value => object => object[key] === value;

// these can be rewritten
const isCuisine = isKeyEqualToValue('cuisine');
const isPrice = isKeyEqualToValue('price');

// these don't need to change
const isBurger = isCuisine('burger');
const isPizza = isCuisine('pizza');
const isCheap = isPrice('cheap');
const isExpensive = isPrice('expensive');

This, to me, is the beauty of arrow functions. In a single line, you can elegantly create a third-order function. isKeyEqualToValue is a function that returns the function isPrice which returns the function isCheap.

See how easy it is to create multiple filtered lists from the original restaurants array?

See the Pen .filter – returning predicates by Adam Giese (@AdamGiese) on CodePen.

Composing Predicates

We can now filter our array by burgers or by a cheap price… but what if you want cheap burgers? One option is to simply chain to filters together.

const cheapBurgers = restaurants.filter(isCheap).filter(isBurger);

Another option is to “compose” the two predicates into a single one.

const isCheapBurger = restaurant => isCheap(restaurant) && isBurger(restaurant);
const isCheapPizza = restaurant => isCheap(restaurant) && isPizza(restaurant);

Look at all of that repeated code. We can definitely wrap this into a new function!

const both = (predicate1, predicate2) => value =>
  predicate1(value) && predicate2(value);

const isCheapBurger = both(isCheap, isBurger);
const isCheapPizza = both(isCheap, isPizza);

const cheapBurgers = restaurants.filter(isCheapBurger);
const cheapPizza = restaurants.filter(isCheapPizza);

What if you are fine with either pizza or burgers?

const either = (predicate1, predicate2) => value =>
  predicate1(value) || predicate2(value);

const isDelicious = either(isBurger, isPizza);
const deliciousFood = restaurants.filter(isDelicious);

This is a step in the right direction, but what if you have more than two foods you’d like to include? This isn’t a very scalable approach. There are two built-in array methods that come in handy here. .every and .some are both predicate methods that also accept predicates. .every checks if each member of an array passes a predicate, while .some checks to see if any member of an array passes a predicate.

const isDelicious = restaurant =>
  [isPizza, isBurger, isBbq].some(predicate => predicate(restaurant));

const isCheapAndDelicious = restaurant =>
  [isDelicious, isCheap].every(predicate => predicate(restaurant));

And, as always, let’s wrap them up into some useful abstraction.

const isEvery = predicates => value =>
  predicates.every(predicate => predicate(value));

const isAny = predicates => value =>
  predicates.some(predicate => predicate(value));

const isDelicious = isAny([isBurger, isPizza, isBbq]);
const isCheapAndDelicious = isEvery([isCheap, isDelicious]);

isEvery and isAny both accept an array of predicates and return a single predicate.

Since all of these predicates are easily created by higher order functions, it isn’t too difficult to create and apply these predicates based on a user’s interaction. Taking all of the lessons we have learned, here is an example of an app that searches restaurants by applying filters based on button clicks.

See the Pen .filter – dynamic filters by Adam Giese (@AdamGiese) on CodePen.

Wrapping up

Filters are an essential part of JavaScript development. Whether you’re sorting out bad data from an API response or responding to user interactions, there are countless times when you would want a subset of an array’s values. I hope this overview helped with ways that you can manipulate predicates to write more readable and maintainable code.

The post Level up your .filter game appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

Designing For Micro-Moments

August 17th, 2018 No comments

Designing For Micro-Moments

Designing For Micro-Moments

Suzanna Scacca

2018-08-17T13:50:09+02:002018-08-17T12:41:01+00:00

A couple of years ago, Google announced a new mobile-first initiative it wanted web designers and marketers to pick up on. This was our introduction to micro-moments.

These are not to be confused with micro-interactions, which are miniscule engagements websites have with visitors when they “touch” key points of the interface. A mouse changes its appearance when a user hovers over a clickable element. A display error appears after a field is incorrectly populated. A checkbox briefly enlarges and changes color after it’s been ticked off. These are micro-interactions.

A micro-moment, however, originates with your visitor. In Myriam Jessier’s “Things Designers Should Know About SEO In 2018“, she sums up Google’s four micro-moments:

  1. “I want to know.”
  2. “I want to go.”
  3. “I want to do.”
  4. “I want to buy.”

Basically, these are four key moments in every consumer’s life when they decide to pick up their mobile device for a specific purpose. As such, it’s your job to know how to specifically design for these micro-moments.

Recommended reading: What You Need To Know To Increase Mobile Checkout Conversions

How You Should Be Designing For Micro-Moments

When a visitor arrives at a mobile website (or app), they’ve come with a clear motivation:

  1. “I want to know.”
  2. “I want to go.”
  3. “I want to do.”
  4. “I want to buy.”

Seems pretty simple, right? However, as Google launched this initiative a couple of years ago, its had time to quietly observe users in these micro-moments as well as the websites that have most aptly responded to them. As you will soon see, consumers have incredibly high expectations for what the mobile web can do for them. Basically, they want you to be a mind reader and anticipate their every need (and even their location) without them having to say a word.

Is that intimidating? It shouldn’t be. You already have all the information you’d ever need to answer that question.

Here is how you should be designing your mobile website to respond to and draw in consumers as they experience these micro-moments:

1. Start With The Data

Google Analytics will help you decipher where they’re spending the most time productively on your website.


Google Analytics Behavior breakdowns

An example of Google Analytics’ visitor behavior breakdowns. (Source: Google Analytics) (Large preview)

Google Search Console will tell you which keywords are most effective in driving high-quality leads to the site.


Google Search Console keywords

An example listing of keywords and associated clicks and impressions for a website. (Source: Google Search Console) (Large preview)

Once you know where exactly visitors see the greatest value in your product, you can then turn to third-party tools like Answer the Public to give you some insights into what relevant questions your users may be asking about you.


Answer the Public sample answers

An example of how Answer the Public provides micro-moment answers. (Source: Answer the Public) (Large preview)

Ultimately, this data needs to tell you all about your customers’ journey before they ever reach you. What exactly was the question that triggered them to pick up their smartphone and do that search? If you can identify those micro-moments, you can start using various design elements to respond to these questions.

2. Respond With Immediacy

According to Google:

People are searching at the exact moment they need something and are looking for places that can meet their immediate need. In other words, when making these on-the-spot decisions, they are more loyal to their need than to any particular place.

Although we’ve heard a lot about customer loyalty to brands in the past, it’s interesting to get Google’s take on this matter.

While consumers may indeed still remain loyal to brands that take very good care of them and produce a high-quality product nearly 100% of the time, this opportunity to steal attention from those customers in one of their micro-moments is real. Do that enough times and your brand and website could realistically win that customer over so long as you are there every time they go searching to fill that need.

One of the ways you can do this is by providing users with instant solutions. Is your business open now? Can you mail out that new product same-day? Will there be an open table at your restaurant tonight? Answer that immediately and you could find conversions increase dramatically.

Take the Delaware State Fair website, for example.


Delaware State Fair gives users what they need to know

The top of the Delaware State Fair home page gives users easy access to everything they want to know and do. (Source: Delaware State Fair) (Large preview)

Look at the top of the homepage. There are the dates of the fair, which probably answer one of the most commonly searched questions. There is a link to the concert lineup as well as calendar, which answers anything people would want to know about special events they might want to go to. And then there’s a button to buy tickets right away. It’s all right there.

Office Depot is a company that also explicitly addresses immediate needs:


Office Depot includes time-driven design elements

The Office Depot mobile site uses a variety of time-driven design elements to satisfy visitors’ needs. (Source: Office Depot) (Large preview)

As you can see in the example above, Office Depot uses a number of design tactics and elements to play into this need for immediacy.

  • There is a search bar at the very top. Consumers don’t have to even bother with navigation or scrolling through pages if they don’t want to/have the time to.
  • You’ll also see that the closest store’s hours are posted and boldly tell me how quickly I can have any products available in store.
  • Finally, you have the promotional categories for upcoming needs for parents that are about to send kids back to school.

Another website is Universal Studios Orlando; it does a great job sparing mobile users the trouble of sifting through irrelevant information and instead gets them to exactly what they need:


Universal Studios provides immediate research and booking options

Universal Studios includes immediate options for research and booking on the home page and navigation. (Source: Universal Studios) (Large preview)

Aside from a single banner at the top of the home page, the Universal Studios website design gives visitors exactly what they want right away. The navigation includes only the most pertinent links to information and booking as does this succinct section on the home page. There’s really no time to waste when the options are so clear.

And here is one final example of a website that deals in immediacy, albeit with a more subtle design technique: Nordstrom:


Nordstrom uses color for immediacy

Nordstrom appeals to immediacy with this one subtle trick. (Source: Nordstrom) (Large preview)

As you can see, this is a pretty typical e-commerce product page. However, there’s one key difference: Nordstrom is subtly calling attention to its Anniversary Sale and the main reason why there is a significant price drop for this purchase. Rather than use an obtrusive pop-up to announce the sale and pester users to shop, it’s made the price change directly on the page and drawn attention to it with the highlighted text.

3. Respond With Relevant Content

According to Google:

Not only have mobile searches for ‘best’ grown over 80% in the past two years, but searches for ‘best’ have shown higher growth among ‘low-consideration’ products than ‘high-consideration’ products. In other words, we’re all becoming research-obsessed, even about the small stuff.

We understand that the opinions of family, friends, and colleagues matter greatly in the minds of consumers. But as more and more of them to turn the web to make their purchases, it means being open to trusting other opinions online as well — ones that may be more conveniently expressed from a company’s website, from an influencer’s blog, or from social media.

Wherever those words of wisdom happen to come from, it’s important to take Google’s research to heart. With so many consumers now obsessed with this idea of having the best of everything and being able to get it in a pinch, your website needs to be the answer to that question.

But that’s the tricky part. According to Google, it’s not as simple as being a dog food manufacturer and configuring your site to be the answer to:

“Best Dog Food”

Consumers experience these micro-moments at a granular level. Sure, there may be some who think, “What is the best dog food?” But isn’t it more likely that question would be more specific in nature? For instance:

  • Best puppy food?
  • Best grain-free dog food?
  • Best vegan dog food?

Let’s take a look at Google, for example. Here’s a variety of searches for a singular “best of” concept:


Best searches example from Google

Example of the variety in “Best” searches in Google. (Source: Google) (Large preview)

As you can see, it goes beyond the basic questions. Through your design and your content, you must be ready to answer the most relevant questions your users have about your product or service.

With content, you’ll be able to answer many of the “I want to know” questions that are related to the brand with things like:

  • Informational pages regarding services and products.
  • Whitepapers, ebooks, case studies, reports, and other long-form content that provide heavily researched answers on related matters.
  • Blog posts, vlogs, podcasts, and other shorter content that can dabble more in appealing to the emotions of consumers.
  • Tutorials and guides that directly answer questions that consumers are asking.

As far as the design piece is concerned, it’s your responsibility to highlight these pages, so visitors don’t have to dig through various parts or layers of the site (like the footer or secondary navigation) to find their answers.

Google told them it was here, so it’s your job to get them right to it.

The navigation will play a big part in this, as evidenced by Globus Journeys:


Globus answers users in the navigation

Globus Journeys provides answers to micro-moments in the navigation. (Source: Globus Journeys) (Large preview)

As you can see in this example, Globus Journeys answers many of those micro-moments right within the navigation: tips on touring (Touring 101), tips on travel best practices (Travel Tips), deals available for travel (Deals & Offers), etc.

Another way to use navigational design to inform visitors on what they’ll learn/know from this experience can take place on the blog. Salesforce has an interesting example of this:


Salesforce has informative blog navigation

Salesforce includes a navigation menu for the blog. (Source: Salesforce) (Large preview)

There is the standard navigation for the Salesforce website, and then there is the navigation that’s specific to the Salesforce blog. This gives you — as the designer and planner of the site’s layout — a chance to better and more clearly organize content found within it. So, when visitors show up and want to know tips specific to one of those categories, it doesn’t require random searches or (even worse) endless scrolling through a full blog feed.

Another way you can more quickly and thoroughly inform visitors on topics of interest to them is by using strategically placed sections within blog posts.

While you likely won’t have anything to do with the writing of a website’s blog content, you will have control over its layout and formatting. The first thing you can do to expedite the knowledge acquisition process is by using callouts to detail and link to the various sections covered on the page as Be Brain Fit does:


Be Brain Fit has an index of topics

Be Brain Fit calls out a linkable index of topics from the blog post. (Source: Be Brain Fit) (Large preview)

Of course, the post itself is easy to scan, so readers could guide themselves to the most relevant parts. However, by placing this towards the top of the piece, you’re enabling them to get right to the information they seek.

I’m also going to suggest that pop-ups would be helpful in this matter.

I know, I know. Mobile pop-ups can be annoying, but not when they’re used properly as Fit Small Business has done here.


Fit Small Business uses a helpful pop-up

Fit Small Business not only provides all the information needed, but also offers an alternative solution to what they seek. (Source: Fit Small Business) (Large preview)

I encountered this blog post after doing a search for the best way to create a Facebook page. This was one of the links on the first SERP. I was actually quite pleased with the post as a whole. It broke it up into easy-to-follow steps, attractive and informative visuals, and got me the answer I needed.

However, I was especially pleased to see the bottom banner pop-up after I finished getting through the post. Not only has Fit Small Business attempted to reach its audience by providing helpful content, but it’s also providing an alternative solution to anyone who got here and realized, “Eh, I really don’t want to bother with this on my own.”

4. Respond With Geotargeting

According to Google:

Looking for something nearby — a coffee shop, noodle restaurant, shoe store — is one of the most common searches we do. In fact, nearly one-third of all mobile searches are related to location.

Here’s the thing though: users aren’t using “near me” qualifiers as much anymore.


Near me qualifiers dropping in use

Google demonstrates how location qualifiers are decreasing in use. (Source: Google) (Large preview)

According to Google, this is because many consumers now assume that search engines, websites, and mobile apps are tracking this sort of information already. They expect that if they search for something like “dog food,” Google will automatically serve them the most relevant results — and that includes taking into account location proximity.

In Google’s research, it found that about two-thirds of mobile consumers are more likely to buy something from a website or app if information is geographically personalized. There are a plethora of ways to communicate this local-friendliness to visitors — through the copy, through various design elements, and even photos.

Google is a pioneer in this space and so I want to give it a special shout-out in this section for what it does with search results:


Google auto-populates search questions.

Google’s auto-populated search results aren’t just for Google. (Source: Google) (Large preview)

The biggest thing to take away from here is the fact that Google provides its users with auto-populated search recommendations. These are based on the users’ geography, behavior, history, as well as what Google knows about the query itself. As you can see here, it expands on Baltimore to provide more specific results based on the area of the city in which the user wants to drink.

With AI-assisted search functionality, any website can offer this same level of smart search for its users.

Of course, you first need to get access to visitors’ geographic data before you can provide them with these kinds of smart and geographically relevant results. One way to do this is to require them to sign in and fill out a profile with these details. Another way, however, is by serving them with this geotargeting request as Best Buy has done:


Best Buy asks for geo access

Best Buy requests for access to users’ geographic location. (Source: Best Buy) (Large preview)

Once you have access to a visitors’ current location, however, you can start providing them with information that helps them with the “I want to go”, “I want to do”, and the “I want to buy” micro-moments that caused them to reach for the phone in the first place.

Here is what the Best Buy website shows me after I granted it permission:


Best Buy provides geo-specific details

Best Buy uses its visitors’ location to provide helpful in-store visit details. (Source: Best Buy) (Large preview)

The top of the page now displays the nearest location to me as well as opening hours. As I peruse the rest of the site, I will receive relevant information regarding in-store product availability, buy-online-pick-up-in-store options, and so on. This is a really great option for businesses with a sales website and brick-and-mortar location that want to merge the two experiences.

You could also benefit from using this on websites that offer services, appointments, and reservations. Here is an example of what The Palm Restaurant does with my information:


The Palm Restaurant geotargeting

The Palm Restaurant streamlines the reservation process with geotargeting. (Source: The Palm Restaurant) (Large preview)

To start, it uses my information to let me know right away if there even is a location close to me. Philadelphia isn’t too far, but it’s still nice to have the address fully displayed so I can make up my mind about whether I want to dine there. And, if I do, I can choose the “Reservations” button above it.

What’s especially nice about this is that the reservation form is pre-populated:


The Palm Restaurant streamlines conversion

The Palm pre-populates its reservation form based on user information. (Source: The Palm Restaurant) (Large preview)

As you can see, it’s used a mixture of my geographic location along with the most popular reservation types (i.e. two people at 7 p.m.) to pre-populate the form. This saves me, as the user, time in filling it out and making my reservation.

5. Respond With Convenience

According to Google:

Every day, people are becoming more reliant on their smartphones to help make last-minute purchases or spur-of-the-moment decisions. In fact, smartphone users are 50% more likely to expect to purchase something immediately while using their smartphone compared to a year ago.

Recently, I wrote a post about what you need to know to increase mobile checkout conversions. The underlying message was that mobile consumers have certain expectations that need to be met if you intend on converting them there (as opposed to switching back to desktop).

  • Convenience in getting the information they want is one of them.
  • Speed in getting to and through checkout is another.
  • Handling their contact and payment information securely is the final piece.

Clearly, web designers are doing something right as over half of smartphone users reach for their phone to buy something and subsequently do. But it can’t stop with the 10 tips offered in that article. You need to be able to predict what they’re going to purchase and what exactly they want to do when you catch them in those exact micro-moments.

Let’s use UPack as one example.


UPack shows a price quote form first thing

UPack includes a price quote form at the very top of the website. (Source: UPack) (Large preview)

At the very top of every page is a short price quote form that asks only the most pertinent details they need in order to provide a quote to interested customers. By anticipating that’s what they’re looking to do when they visit a moving company’s website, UPack likely experiences very high conversion rates.

However, if someone should arrive at this form and wonder, “Should I even bother with a quote from UPack?”, they’ve provided an answer to that on the next step down on the home page:


UPack's explainer graphic reaches users on the fence

UPack uses an explainer graphic to sell the value of its service right away. (Source: UPack) (Large preview)

This explainer graphic is simple. It includes four points and shows how exactly someone uses the UPack service to move their home from one destination to another. When someone arrives there with the intention of getting help with their move, UPack has already made it all the more simple in just one scroll and two panels of the home page.

Then, you have a company like HostGator that doesn’t waste any time at all:


HostGator provides shortcut to purchase

HostGator’s home page includes smart design callouts that sum up its services. (Source: HostGator) (Large preview)

If someone shows up on a web hosting company’s website — especially one that is well known as they are — of course they know what they want to do. Now, they could hop into the navigation and dig deeper into the various hosting plans (which some may do). However, HostGator is probably hoping to appeal to two specific audiences with these “Buy Now!” callouts on the home page:

  • The web developer who knows exactly which plan he or she needs, and doesn’t need a full page to explain the benefits to him.
  • The small business owner who doesn’t know a thing about web hosting, but trusts HostGator’s good name and just wants to get their web hosting purchases ASAP.

This is a really good choice of design techniques if you know that a good portion of your audience will be immediately ready to buy upon entering the site. If they don’t have to click through to another site, don’t make them do it.

And, of course, CTAs, in general, are an important element to use when designing for micro-moments. When they’re designed well — colorful, large, well-labeled — you’re essentially giving your users a shortcut to conversion.

BarkBox uses a number of these right on its home page:


BarkBox's CTA shortcuts

BarkBox has a number of CTA shortcuts available on its website. (Source: BarkBox) (Large preview)

Since the brand is particularly well-known among dog owners, this is a good move. While there are some people who enjoy scrolling through the site to see the funny dog pictures and find out more about what’s in this month’s BarkBox, if they’ve arrived here on mobile, they shouldn’t have to wait to subscribe. BarkBox provides those shortcuts in a number of locations, ensuring there’s no friction between its customers and their goals.

Wrapping Up

It’s pretty amazing to watch the web change so quickly as consumers become more trusting of their mobile devices. Now, nearly two years after Google first began recommending that we design with micro-moments in mind, it appears that these suggestions have really paid off.

Designing for micro-moments gives us the opportunity to more effectively reach consumers in their moment of need. This, consequently, means reaching consumers who are in a more purchase-intent mindset as opposed to ones casually browsing the web. If you can use your data and design to actively reach consumers in their micro-moments, you can effectively increase your mobile site’s conversion rate in the years to come.

Smashing Editorial(lf, ra, yk, il)
Categories: Others Tags:

The Real Problem With Pre-Made Themes

August 17th, 2018 No comments

Designers, developers, site owners… lend me your eyeballs for a bit. There’s something rotten in the state of pre-made website themes. Alright, I’ve offended The Bard quite enough. But you get my point, right? Themes have gotten a bad rap for a variety of reasons: they can have bloated code, content must be designed to fit in them rather than designing them to fit the content, et cetera.

But they’ve also gotten really good. Many are made to be modular, so you only use and load the code you need. People have gotten a lot better at coding things to load fast, and there’s a theme for nearly every conceivable need. So maybe it’s not as optimized as it could be, if you’re not getting Amazon levels of traffic, regular hosting should be fine, right? And again, there’s a theme for every conceivable need! It’s just so convenient.

Wrong, wrong, wrong, (mostly) wrong.

Let me tell you a little story. A long, long time ago in February of 2018, I had an idea. Well, really I had a few ideas of things I desperately wanted to write about, but no one was paying me to do it. And honestly, keeping up a blog on the topics I had in mind wouldn’t be all that feasible. I like my projects to have a beginning, middle, end, and perhaps most importantly, a deadline.

So I thought, hey, why not make some niche/authority sites on these topics so dear to my heart? There’s no reason niche sites have to be predatory glorified ads with terrible aesthetics and UX. I could make them better. And I could just leave them up when I was done, with minimal updates. And hell, I don’t even need to design them! A wiki or knowledge base theme for WordPress or some other CMS would do quite nicely for my purposes.

I found plenty of themes…I very nearly dropped money on

And so I went theme hunting. I found plenty of themes in the categories I had in mind, including some absolutely beautiful premium themes I very nearly dropped money on. That would have been a terrible waste of my cash.

It’s because, you see, each and every one of these themes depended on JavaScript for their most basic functions: displaying any content at all, navigation, and search. (Now I told myself I wasn’t going to get back into this particular crusade. I told myself I could stop writing about how completely depending on JavaScript is a terrible idea. I wasn’t going to do this anymore, darnit!)

But people are getting ripped off, and I can’t stand for that. If you’re selling a theme that depends on JavaScript to work at all, you’re selling a site that is going to break under certain conditions. Whether it’s a slow connection, a plugin incompatibility, some ad network gone rogue, or a random browser hiccup, it’s going to break. If you allow a web product that’s intended for daily use to be that fragile, that’s an accessibility issue, and it’s a rip-off.

It’s one thing to build a JavaScript-dependent site for a client who knows the risks and chooses to take them. It is quite another to sell templates like that, especially without any warning. These things are only sometimes implemented by professional designers or developers who want to save time. They are very often implemented by beginners who are just learning a bit of HTML even as they use your theme.

More than that, these were wiki and knowledge base themes. Those are the kinds of sites people go to when they need help. Customer support and educational sites should be the least likely to break, period. This is a case where both the customer and the user are being let down in a big way.

People will always want flashy stuff, fine. We can’t help that fancy animation grabs the eye, and I don’t blame theme designers for using it as a selling point. But you owe it to your customers to implement fall-backs for every JavaScript element that might break. You owe it to them to at least make your basic layout, navigation, and any forms work under just about any condition. Ancient browsers notwithstanding.

you owe it to your customers to implement fall-backs for every JavaScript element that might break

In my mind, a lack of progressive enhancement, or at least graceful degradation, is the single biggest accessibility nightmare to plague the wonderful world of pre-made sites and themes. Customers are buying these things without knowing exactly what they’re doing, and it’s bound to end in misery. And here I thought bad planning was the biggest problem for theme-based sites.

Yes, implementing fall-backs for everything is difficult, but that’s why you charge money for these things. If they were all that easy to make, they could all be free, right? No, I don’t expect you to code your themes for every version of IE, and yes I realize that most premium themes come with support of some kind or another.

Theme authors just need to recognize that when JavaScript breaks, it most often only breaks for some of the end users, and only some of the time. But those end users could have turned into paying customers for the people who bought the themes, and now they probably won’t. And that’s on us designers and developers, no one else.

Well, now I have to go design my own wiki/knowledge-base style theme (probably for Grav CMS, at this point), because somebody needs to do it right, and it might as well be me. To quote Taylor Swift, “Look what you made me do.”

Add Realistic Chalk and Sketch Lettering Effects with Sketch’it – only $5!

Source

Categories: Designing, Others Tags:

Monthly Web Development Update 8/2018: The Cost Of JavaScript, Ethics In Open Source, And QUIC

August 17th, 2018 No comments
SmashingConf New York 2018, with Dan Mall, Sara Soueidan, Sarah Drasner and many others.

Monthly Web Development Update 8/2018: The Cost Of JavaScript, Ethics In Open Source, And QUIC

Monthly Web Development Update 8/2018: The Cost Of JavaScript, Ethics In Open Source, And QUIC

Anselm Hannemann

2018-08-17T11:57:10+02:002018-08-17T12:41:01+00:00

Building technology and software has become a very responsible job. People trust the products we create, and they can have a significant impact on their lives, too. Considering this, we not only need to think about inclusive solutions, but also stand up and advocate for ethics, reliability, and security. It’s a position that gives us power.

Eric Meyer published an article elaborating the problems which an HTTPS-only web is bringing along. In it, he reveals that developing countries suffer a lot from this development as they often have bad internet connections and, due to the encryption, they now experience more website errors than before. Ben Werdmüller jumped in and published the article “Stop building for San Francisco” in which he points out one of the biggest problems we have as developers: We use privileged hardware and infrastructure. We build experiences using the latest iPhones, Macbooks with Gigabit or fast 4G connections but never consider that most people we’re building for use devices and infrastructures that are far from being that well-equipped. Making the web more secure is a great idea, beyond question, but we should also keep in mind the consequences that the latest tech and our design decisions might have for others.

News

General

UI/UX

  • Ethics for Design is a project where twelve designers and researchers from eight European cities discuss the, sometimes harmful, impact of design on our societies and what designers can do to work for the good of all and not just a few.

Tooling

  • Prashant Palikhe wrote a long story about the art of debugging with Chrome’s Developer Tools, which I can highly recommend as it’s a very complete reference to get to know the developer tools of a browser. If you use another browser, that’s not a big problem as most tools are quite similar.
  • WebP is an image format with a couple of nice features and likely one of the best-known new formats besides the common JPEG/PNG ones. However, creating WebP images can still be a challenge, so Jeremy Wagner wrote a guide on how to convert images to WebP.
  • Douglas Creager introduces the new Network Error Logging which allows you to instruct user agents to collect the same set of information that would appear in your server logs.
  • Many of us are addicted to communication tools like Slack. The folks from Wildbit decided to shut down Slack for a week — with a significant effect on how they work. An interesting case study about how we tend to get too comfortable with a useful tool and don’t use it as we should anymore. From time to time, it’s important to reset our minds.
  • Dennis Reimann published the first stable version of UIEngine, a workbench for UI-driven development.

Security

  • A new Observer is around: The ReportingObserver API lets you know when your site uses a deprecated API or runs into a browser intervention. So far, it’s available in Chrome 69. You could easily use this to send errors that previously were only available in the Console to your backend or error handling service.

Web Performance

A QUIC handshake only takes a single round-trip between client and server to complete, whereas TCP and TLS usually need two. (Image source)

HTML & SVG

Accessibility

JavaScript

  • One year after they introduced their Progressive Web App, Zack Argyle from the Pinterest engineering team takes a look back. It’s important to note why they decided to build a PWA: “Our mobile web experience for people in low-bandwidth environments and limited data plans was not good”. But the results for them are amazing to see.
  • Philip Walton introduces the new Page Lifecycle API which helps us determine page states in the browser more easily via events, such as the page being in the background (not visible), active, frozen or even terminated.
  • Whoops, you all know eval() in JavaScript is bad, right? That’s why we usually forbid its usage in Content Security Policies. But Remy Sharp reminds us that there’s a line of code which is equally bad for security.
  • Addy Osmani researched the cost of JavaScript in 2018 and now shares evidence that every byte of JavaScript is still the most expensive resource we can send to mobile phones because it can delay interactivity significantly. This is a problem especially for not so capable phones that are widely used outside the tech industry.
  • Hidde de Vries explains how we can make page titles accessible in JavaScript Single Page Application.
The Cost Of JavaScript In 2018
What’s the real cost of JavaScript? One of the findings from Addy Osmani’s research: It takes a low-end 2018 phone 32 seconds longer than an iPhone 8 to process JavaScript for CNN.com. (Image source)

CSS

Work & Life

Going Beyond…

  • Tobias van Schneider wrote about why the Sagmeister-Walsh studio is so successful by staying small and why dreaming big but staying small is so important for creative thinking.
  • Ben Werdmüller shares his thoughts on how different it has become to start a business when you’re, for example, in San Francisco. This is a story where $117,000 are considered a “low income” in San Francisco and how this limits ideas.
  • Jeremy Nagel makes us think about the impact of our open-source code: As developers we tend to believe that making our code freely available is an amazing move but we forget that we make it available to bad players as well — to coal miners, to pollution-contributing companies, to those who use people to get rich while mistreating them, to those who rip you off indirectly. It’s not that you can’t do anything about it; you have to be aware of these issues and apply a better license or add a dedicated statement to your code.
  • India has a big plastic waste problem. Since a couple of months, a couple of fishers don’t ignore the plastic problem anymore but collect all the waste in their nets instead, and bring it back to the shore where it’s used to build roads. A great idea of making use of trash efficiently.
Smashing Editorial(cm)
Categories: Others Tags:

Working with refs in React

August 16th, 2018 No comments

Refs make it possible to access DOM nodes directly within React. This comes in handy in situations where, just as one example, you want to change the child of a component. Let’s say you want to change the value of an element, but without using props or re-rendering the whole component.

That’s the sort of thing refs are good for and what we’ll be digging into in this post.

How to create a ref

createRef() is a new API that shipped with React 16.3. You can create a ref by calling React.createRef() and attaching a React element to it using the ref attribute on the element.

class Example extends React.Component {
  constructor(props) {
    super(props)

    // Create the ref
    this.exampleRef = React.createRef()
  }

  render() {
    return (
      <div>
        // Call the ref with the `ref` attribute
        <input type="text" ref={this.exampleRef} />
      </div>
    )
  }
}

We can “refer” to the node of the ref created in the render method with access to the current attribute of the ref. From the example above, that would be this.exampleRef.current.

Here’s an example:

See the Pen React Ref – createRef by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

class App extends React.Component {
  constructor(props) {
    super(props)
    
    // Create the ref
    this.textInput = React.createRef();
    this.state = {
      value: ''
    }
  }
  
  // Set the state for the ref
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ value: this.textInput.current.value})
  };

  render() {
    return (
      <div>
        <h1>React Ref - createRef</h1>
        // This is what will update
        <h3>Value: {this.state.value}</h3>
        <form onSubmit={this.handleSubmit}>
          // Call the ref on <input> so we can use it to update the <h3> value
          <input type="text" ref={this.textInput} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

How a conversation between a child component and an element containing the ref might go down.

This is a component that renders some text, an input field and a button. The ref is created in the constructor and then attached to the input element when it renders. When the button is clicked, the value submitted from the input element (which has the ref attached) is used to update the state of the text (contained in an H3 tag). We make use of this.textInput.current.value to access the value and the new state is then rendered to the screen.

Passing a callback function to ref

React allows you to create a ref by passing a callback function to the ref attribute of a component. Here is how it looks:

<input type="text" ref={element => this.textInput = element} />

The callback is used to store a reference to the DOM node in an instance property. When we want to make use of this reference, we access it using:

this.textInput.value

Let’s see how that looks in the same example we used before.

See the Pen React Ref – Callback Ref by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

class App extends React.Component {
    state = {
    value: ''
  }
  
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ value: this.textInput.value})
  };

  render() {
    return (
      <div>
        <h1>React Ref - Callback Ref</h1>
        <h3>Value: {this.state.value}</h3>
        <form onSubmit={this.handleSubmit}>
          <input type="text" ref={element => this.textInput = element} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

When you make use of callback like we did above, React will call the ref callback with the DOM node when the component mounts, when the component un-mounts, it will call it with null.

It is also possible to pass ref from a parent component to a child component using callbacks.

See the Pen React Ref – Callback Ref 2 by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Let’s create our “dumb” component that will render a simple input:

const Input = props => {
  return (
    <div>
      <input type="text" ref={props.inputRef} />
    </div>
  );
};

This component is expecting inputRef props from its parent component which is then used to create a ref to the DOM node.

Here’s the parent component:

class App extends React.Component {
  state = {
    value: ''
  };

  handleSubmit = event => {
    this.setState({ value: this.inputElement.value });
  };

  render() {
    return (
      <div>
        <h1>React Ref - Callback Ref</h1>
        <h3>Value: {this.state.value}</h3>
        <Input inputRef={el => (this.inputElement = el)} />
        <button onClick={this.handleSubmit}>Submit</button>
      </div>
    );
  }
}

In the App component, we want to obtain the text that is entered in the input field (which is in the child component) so we can render it. The ref is created using a callback like we did in the first example of this section. The key lies in how we access the DOM of the input element in the Input component from the App component. If you look closely, we access it using this.inputElement. So, when updating the state of value in the App component, we get the text that was entered in the input field using this.inputElement.value.

The ref attribute as a string

This is the old way of creating a ref and it will likely be removed in a future release because of some issues associated with it. The React team advises against using it, going so far as to label it as “legacy” in the documentation. We’re including it here anyway because there’s a chance you could come across it in a codebase.

See the Pen React Ref – String Ref by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Going back to our example of an input whose value is used to update text value on submit:

class App extends React.Component {
    state = {
    value: ''
  }
  
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ value: this.refs.textInput.value})
  };

  render() {
    return (
      <div>
        <h1>React Ref - String Ref</h1>
        <h3>Value: {this.state.value}</h3>
        <form onSubmit={this.handleSubmit}>
          <input type="text" ref="textInput" />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

The component is initialized and we start with a default state value set to an empty string (value=''). The component renders the text and form, as usual and, like before, the H3 text updates its state when the form is submitted with the contents entered in the input field.

We created a ref by setting the ref prop of the input field to textInput. That gives us access to the value of the input in the handleSubmit() method using this.refs.textInput.value.

Forwarding a ref from one component to another

**Ref forwarding is the technique of passing a ref from a component to a child component by making use of the React.forwardRef() method.

See the Pen React Ref – forward Ref by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Back to our running example of a input field that updates the value of text when submitted:

class App extends React.Component {
    constructor(props) {
      super(props)
      this.inputRef = React.createRef();
      this.state = {
        value: ''
      }
    }
  
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ value: this.inputRef.current.value})
  };

  render() {
    return (
      <div>
        <h1>React Ref - createRef</h1>
        <h3>Value: {this.state.value}</h3>
        <form onSubmit={this.handleSubmit}>
          <Input ref={this.inputRef} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

We’ve created the ref in this example with inputRef, which we want to pass to the child component as a ref attribute that we can use to update the state of our text.

const Input = React.forwardRef((props, ref) => (
  <input type="text" ref={ref} />
));

Here is an alternative way to do it by defining the ref outside of the App component:

const Input = React.forwardRef((props, ref) => (
  <input type="text" ref={ref} />
));

const inputRef = React.createRef();

class App extends React.Component {
    constructor(props) {
      super(props)
      
      this.state = {
        value: ''
      }
    }
  
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ value: inputRef.current.value})
  };

  render() {
    return (
      <div>
        <h1>React Ref - createRef</h1>
        <h3>Value: {this.state.value}</h3>
        <form onSubmit={this.handleSubmit}>
          <Input ref={inputRef} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

Using ref for form validation

We all know that form validation is super difficult but something React is well-suited for. You know, things like making sure a form cannot be submitted with an empty input value. Or requiring a password with at least six characters. Refs can come in handy for these types of situations.

See the Pen React ref Pen – validation by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

class App extends React.Component {
  constructor(props) {
    super(props);

    this.username = React.createRef();
    this.password = React.createRef();
    this.state = {
      errors: []
    };
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const username = this.username.current.value;
    const password = this.password.current.value;
    const errors = this.handleValidation(username, password);

    if (errors.length > 0) {
      this.setState({ errors });
      return;
    }
    // Submit data
  };

  handleValidation = (username, password) => {
    const errors = [];
    // Require username to have a value on submit
    if (username.length === 0) {
      errors.push("Username cannot be empty");
    }
    
    // Require at least six characters for the password
    if (password.length < 6) {
      errors.push("Password should be at least 6 characters long");
    }
    
    // If those conditions are met, then return error messaging
    return errors;
  };

  render() {
    const { errors } = this.state;
    return (
      <div>
        <h1>React Ref Example</h1>
        <form onSubmit={this.handleSubmit}>
          // If requirements are not met, then display errors
          {errors.map(error => <p key={error}>{error}</p>)}
          <div>
            <label>Username:</label>
            // Input for username containing the ref
            <input type="text" ref={this.username} />
          </div>
          <div>
            <label>Password:</label>
            // Input for password containing the ref
            <input type="text" ref={this.password} />
          </div>
          <div>
            <button>Submit</button>
          </div>
        </form>
      </div>
    );
  }
}

We used the createRef() to create refs for the inputs which we then passed as parameters to the validation method. We populate the errors array when either of the input has an error, which we then display to the user.

That’s a ref… er, a wrap!

Hopefully this walkthrough gives you a good understanding of how powerful refs can be. They’re an excellent way to update part of a component without the need to re-render the entire thing. That’s convenient for writing leaner code and getting better performance.

At the same time, it’s worth heeding the advice of the React docs themselves and avoid using ref too much:

Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy.

Get it? Got it? Good.

The post Working with refs in React appeared first on CSS-Tricks.

Categories: Designing, Others Tags: