emGee Software Solutions Custom Database Applications

Share this

Web Design

A Comprehensive Website Planning Guide (Part 3)

Smashing Magazine - Tue, 03/06/2018 - 03:40

In Part 2, I covered the details of evaluating a plan, choosing web professionals, and determining your website structure. The question of why planning for the web is just as important as planning for anything else associated with your business was covered in Part 1, so head on back to read that part first in case you missed it. In today's final part of this guide, I'll start with a few of the most common approaches in any initial design.

Initial Design: Three Common Approaches

There are, of course, others, including hybrids which combine elements of each, and every design team and every project is different, but there are core approaches to creating a web design.

1. Classic Photoshop mockup approach

Commonly created in Adobe Photoshop (the industry standard) or other design software such as Sketch, the initial design will consist of a visually accurate image ("mockup") of the home page and at least one internal page.

Your business' visual branding elements should be applied here. If you have well-defined graphics in addition to your logo, they will dictate the design of the site. However, if your brand lacks detail, the designer will do their best to create work that accurately reflects the business, working with your existing graphics as a jumping off point.

Following is a short list of key points for successful mockups. We'll assume the designer is working in Photoshop, however, these guidelines also apply to other design programs.

  • Start with a pre-made grid with pre-drawn, pixel-accurate guides. Some designers create their own, while others may adhere to a pre-set grid system. Whatever the case, it's important to have a clean template to start. Make your canvas wider than the width you're designing to, so you can add notes on one side and get a feel for what the site feels like when floating in a wide browser window.
  • Add the color palette and basic branding elements (i.e., fonts) in the margins of the canvas so you'll have it for reference when viewing on screen or in print.
  • Draw everything to exact pixels, and draw clear guides and/or slices around design elements. This becomes critical when the front end developer later creates the HTML from the mockup, however, your design will only be pixel-accurate when displayed on a ‘big screen' device.
  • Organize all design elements with a logical folder/subfolder structure, and label each item clearly.
  • If the designer will be handing off their files to an HTML developer, this is especially important. Name your folders and layers for their content so there's no confusion later. For example: "Sidebar — events header" is clear, "Layer14 Copy Copy Copy" is not.

Getting the process just right ain't an easy task. That's why we've set up 'this-is-how-I-work'-sessions — with smart cookies sharing what works really well for them. A part of the Smashing Membership, of course.

Explore features →
  • Make clear notes dictating fonts, alignment, repeating background elements, gradients and anything that will need to be implemented with CSS techniques. In Photoshop, the sticky note feature is good for this. If unclear, ask the person who will be converting your design into a working page.
  • If using a common style for headers, navigation, or other design elements that appear throughout the site, consider making separate Photoshop documents for them. Some designers find it easier to "chunk it down", especially in big projects.
  • Use realistic content. Designers often use greeking ("lorem ipsum") to fill space, which is ok for body copy. However, for headlines, titles, events, etc., try to use realistic copy. Consider the two following headlines. Layout considerations are different for each:
    • "Widgets, Inc. Wins Green Manufacturing Award"
    • "Widgets, Inc. Employees Win Landmark Court Case Affirming Employee Right To Petition For College Tuition Reimbursement When Training Is Relevant To Work Role"
Large preview The problem with this method

When you design pixel-perfect mockups, you can be assured that the website's appearance will be very close on the desktop web — but that's it. The minute you switch to a different device, it will change. So at the very least, you'll want to either convey to the business how the design will change as it is viewed on smaller screens (tablet, smartphone) by showing a site with similar layout, or design additional mockups at common screen sizes. As you can imagine, this is a lot of additional design work, and if you change an element on the desktop-focused mockup, you'll have to change it on the others too. Here's the smartphone view.

Large preview 2. Design in the browser

With the rise of responsive web design, some designers are moving away from the Photoshop mockup approach, instead using responsive frameworks like Bootstrap or Foundation, or tools like Froont or Typecast. These tools allow very rapid, iterative design that allows you to see how the site will look on different devices.

You may still use Photoshop or other graphic design tools to create stylized elements to place within the design, but the bulk of the design will happen outside these tools. There is no good way to show the business "exactly what it will look like" so for designers used to making pixel-perfect mockups for the desktop web, in-browser design may not be the best approach. For many, this method also represents a major change to their process and can take a while to get the hang of. Most see this as a necessary evolution, since a Photoshop mockup can only represent one of the many "frames" in which your site's content is displayed, and the world of web is moving rapidly toward designing for multiple platforms from the get go.

When it's time to write the HTML, CSS and Javascript that will make up the site, you can either stick with the framework you used initially to create your design iterations, adapt its code, or write your own from scratch, using your framework designs as a guide.

3.Element collage (also know as style tile, style collage)

With this approach, the designer will assemble a range of elements that make up a website including header, navigation, icons, sample photography, illustrations, forms, interactive elements, and anything else deemed necessary to get a good sense of the site's look and feel. Additionally, depending on the design tool, these elements may be laid out in such a way as to show how their appearance will change in unison with the screen size. This is typically combined with some kind of graphic mockup of at least the home page and few internal pages. (It can be hard for businesses to visualize how pages in a site will look based solely on an element collage.)

Note: These sample images are not to scale — our Photoshop version of the element collage is one long page, 1500X4500 pixels, so we can't fit it here in one piece.

Large preview

For designers (and businesses) long used to the Photoshop mockup method, this is also a new frontier, and requires a change in perspective. With a style prototype, you're not trying to layout a page exactly, but rather, to show the key parts of the site and get feedback on the general look and feel. Because a responsive site must change in appearance radically as the screen size changes, this method is much more about about the parts of a site and getting a feel for the direction the design is heading. You're not showing the site as a whole, let alone making a pixel-perfect representation of exactly how each and every page will look.

This can save a lot of time, but again, if the business isn't comfortable (or trusting) enough to let the designer make structural decisions later on down the line, this method may be a tough sell. That said, it really can create a flexible environment in which to rapidly create web designs for myriad platforms.

While the principles of graphic design are timeless, the approaches used for website design will change and evolve over time. I highly recommend you watch Design Deliverables for a Post-Comp era to discover the value of this approach.

When using this the element collage method, the business must accept there is no exact, precise, final draft of a given page, only layout guidelines to agree upon. The very nature of responsive sites is to adapt their content to the capabilities of each device, so the businessmust not expect to approve set-in-stone layouts prior to the development phase. With an approved style prototype, a designer may want to return to wireframes or working prototype to work out all the layouts your project requires. Then when it comes to build the site, you will assemble the elements of your collage into the visual structure of each unique layout.

There is much discussion and debate in the design community about the best tools, methods, and process for creating web designs. Designers tend to feel very strongly about which is the "best" method, and while that's understandable, it's important to use the most suitable process for the project and the business. It's smart for designers to get comfortable working with an array of methods and systems, and broaden their horizons when a project allows.

Author's note
I was very hesitant to include some of the following content, because it highlights serious tensions in the business-designer relationship. While it may seem overly critical of business owners, I believe it is of great value to businesses because so much time and money is at risk in a website project.
In the interest of diplomacy and preserving client relationships, designers probably won't voice these frustrations to business owners, but the following issues can and do derail projects. Design approval and revisions

Regardless of which design method was chosen for the project, when the design is complete, the results are are shared with the business for approval, and there is often a (hopefully short) revision process. The revision process involves the the designer and key stakeholders going back and forth a few times, trying different edits to the design until the design is approved.

Design by committee: don't do it.

A common (and completely avoidable) problem at this stage is the consideration of too many opinions, simply having too many cooks in the digital kitchen.

To help ensure a smooth process, the business must assign one person as the point of contact for the design team. That person is responsible both for communicating with the designer and for making final decisions about design direction.

Certainly, it is important to solicit feedback on design, and project stakeholders have valuable critique to offer, helping guide the design process so that the end result accurately represents their business.

Additionally, in some instances, review by legal and/or technical staff is needed. However, having the entire company offer input, and lending equal weight to all feedback leads quickly to nobody being satisfied. The best possible way to ensure a muddy, unfocused design is to give everybody input and then to run around making all the changes proposed.

Generally speaking, in small businesses or organizations, having any more than five people provide design feedback is a recipe for gridlock. The fewer the better, five is the maximum. These five (or fewer) people will solicit feedback from their subordinates or department colleagues, but that input should be compiled by each stakeholder and presented as a unified, single opinion. In other words, don't invite fifteen people to a design review meeting. Weed out all the back and forth before you go to the designer with input. It's also very important to distinguish between objective design concerns ("does this color scheme really suit our bakery?") versus personal design preferences ("I love the color blue — let's use a lot more blue").

Design is not an arbitrary pursuit. There is good design and bad. There are rules to be followed, best practices to be adhered to, and as long as planning has been done properly, design decisions are almost never really a matter of taste. That is, there's a good reason the designer used that exact blue, in that exact spot, or that font at that size. All of those little choices communicate things to the user. They may feel insignificant, but in reality, all these choices the designer makes are important. They can drastically affect the way the site functions and how it is received. Unfortunately, many businesses fail to understand that just because they like it doesn't mean everybody else will, and doing what's best for conveying the soul of the business is what the designer is hired to do. Opinion shouldn't enter into it unless absolutely necessary.

When egos rule

Any experienced designer has dealt with decision makers who have the dreadful combination of strong ego and poor design sensibility. In the worst case, designers will be asked to use a logo the CEO developed in Microsoft PowerPoint, or colors and fonts totally unsuited to the business' image. This, unfortunately, comes with the territory of being a designer. Sometimes it's possible to diffuse this by placing the offending artwork in a grid alongside professionally designed material from competitors or similar companies in the industry — Pinterest is a good tool for this.

If a competitive review was part of your needs assessment, you may want to refer to their brands for reference. The hope is that the business can see how awful their version looks next to the competition and rethink their commitment to the bad idea. Ultimately, however, decision makers can and do ruin projects by insisting, contrary to all available evidence, that their design sense should take priority over established design principles.

Help! They won't budge!

Readers of an earlier version of this book asked for ways to deal with the ego problem. I wish I had a clever or useful answer for you. Suffice to say this is a problem with people, not technology. Make your best case for the value of good design, fight your best fight, then be prepared to let it rest.

Design tension: designer vs. the business

Designers often deal with tension between their informed concepts of design and business' uninformed design critiques. This is best illustrated by the "bad idea" conundrum. The business will request a design feature that's either ugly, unworkable, or just a bad idea. (This is so common that there are many websites which chronicle clueless businesses and the headaches that result in this dynamic1.) The designer will respond somewhere on the continuum between "that's horrible, we won't do it" and "well, if that's what you prefer...". This response is dependent on a variety of ever-shifting factors, including:

1http://clientsfromhell.net, http://theoatmeal.com/comics/design_hell

  • When designer hopes to get paid.
  • How emotionally invested designer is in the project.
  • How much time the designer has invested in the design phase, and how much delay will result from implementing the bad idea.
  • How high the stakes are — how much damage the bad idea will do to the site as a whole.
  • Personality, businesses' willingness to take constructive counsel about their ideas.

Every project is different. When designers deal with businesses who continually request features that are ill- advised, at some point they may write off the project altogether. At a certain point, it's just too exhausting to continually explain why centered, bold paragraphs in red, WRITING IN ALL UPPERCASE, crazy Flash animations or poor quality photography make an ineffective website2. The designer's attitude rapidly shifts from "let's make something really great that we're proud of" to "let's just get it done so we never have to look at this again."

2Other mood killers include autoplay videos and fonts most often used in children's books.

While considering the above, also realize that there's another side to this coin. People problems can also crop up on the designer end of the spectrum. Some designers' skills may not be up to par, they may refuse to listen to valid criticism of their work, or may not value the informed input of the business. A good way to avoid this is by getting good references from designers' past clients.

Consider the content

Think about expansion. For example, you may have a news section. To start, you have six news items. That's fine. You'll make a main news page with summaries and link the summaries to a detail page. But what happens when you have ten, twenty, or fifty news pieces? Now there are other considerations. Do you want to archive old news? Create pagination? Only show the most recent ten items? This should be considered in the design process. Plan around content as much as possible in the design process, and think ahead wherever you can — plan for the content you will have, not the content you have right now.

Web style guide

A style guide is where proper planning shines. A style guide will consist of all the design, layout, interactive (i.e. JavaScript) and type elements used throughout the site in one location. This is usually done in HTML, so if you're a designer who doesn't code, you'll need to create a mockup for your style guide and deliver it to your front end developer along with the rest of your designs. If you've used the element collage method covered earlier, you may not need to repeat yourself in a separate web style guide. If you're using the classic Photoshop mockup method, you will need one. Elements of a style guide include, but are not limited to:

  • Navigation styles
  • <h1> through <h5>, also known as header tags
  • Paragraphs
  • Lists
  • Block quotes
  • Italics, bold face, underlines
  • Links, including active, hover and visited states, that is, the appearance of links, including when hovered over with the mouse
  • Icons
  • Use of images and image style
  • Use of background images or "watermarks"
  • Forms.

This article from Canva explores 10 web style guides for well known companies. You can also use an online tool like Frontify.

Using A Pattern Library

For websites of larger scope, you might expand the web style concept to the more robust pattern library, which explains how various elements appear and how they are handled. Sample code for these elements is usually part of the library. It's not just a picture of it, but the thing itself. For example, what does a form look like, what happens visually when it has errors, what is the process for comment submission, etc.

Approved mockups, element collage and wireframes, along with the style guide, are used as the building blocks for the next steps of development.

HTML/CSS Creation

Using the designs and style guide, an HTML/CSS expert (the front end Coder) will create HTML templates which accurately represent the design as approved. In some cases, templates will appear identical to mockups, however, where Photoshop was used for mockups, subtle differences are to be expected.

Your front end coder might also need additional guidelines and assets related to designs, like color palettes, specific images, icons, and — if not explicitly noted already — design rules like margins and padding. Make sure you know what all the deliverables will be before you start sending files. If designs and style guide were created with plenty of attention to detail, there should be few questions or guesswork at this stage; work should be humming along.

Interactive Element Creation

Interactive elements may be as simple as a drop-down menu, or as elaborate as a pie chart creator. These elements are typically developed with JavaScript, often using a script library like jQuery. At the most general level, this consists of assembling (and writing) a set of instructions that interact with pages on your website. There may be interactivity between site and server to consider too. You might be connecting APIs3, making something like a booking or calendar system etc., or using widgets from third party services.

3 Essentially, a bridge between one or more systems. For example, Facebook offers an API that allows you to pull in posts from your wall to an unrelated website.

 CMS Integration

At long last your brilliant design has been converted to code and is ready to be integrated in a Content Management System (CMS). It's well on its way to becoming a website!

The individual or team tasked with doing the "stitching" of the code to the CMS will provide you with a login for the control panel of the CMS, which allows you to enter the content, including text, photos, videos, and documents. Most writers prefer to cut and paste from Microsoft Word.

Depending on the specifics of the CMS selected, you may be able to do this without issue, retaining simple formatting like bold, italics, and lists. However, the CMS may strip out this formatting when you cut and paste, requiring you to add it back. While sometimes tedious, this insures your content remains neat and orderly, which makes it more easily indexed by search engines, more easily printed, cited and converted to other formats.

Although in reality this process is quite involved, I've left out the details because the exact process will be unique to each CMS, and doing this well relies on the expertise of the Web/CMS Developer.

Training And Documentation

While modern CMS can be very user friendly, it's important to coordinate training for the people responsible for entering content. When possible, on-site training is best, with web conference a second choice. Training works best in very small groups — 5 people or less. Additionally, having people actually follow the steps needed to complete a task on their own, (rather than just having them watch the trainer and try to remember how to do it when they're on their own) is much more effective.

Training should be supported by documentation, which can take many forms:

  • Step-by-step video ("screencast")
  • PDFs with screenshots
  • Printed guidelines
  • Contextual help (built in to the CMS).

Sometimes documentation combines some or all of the above. Whatever you choose, keep in mind the skill level of the people entering content. Many people who work in offices are competent at Microsoft Word and email, but can be challenged by basic but necessary "design" tasks like sizing and cropping images. Also remember that the business probably isn't working with the same set of professional design tools that the designer is, so make allowances for the business' technological concerns as well.

It's a good idea to save the writing of documentation until as close to the end of the project as possible. Remember that if you change something in the CMS mid-project, you may have to update documentation to match. This can be very time-consuming (and confusing too), so try to coordinate the parts of your project so the documentation is written once the content entry process has been finalized.

Puttin' it all together...

At this point, having followed the preceding steps, you should now be sitting on a pretty solid website. Regardless the size of your project, now is a good time to:

Review your content once again, checking it against the points listed under writing for the web above.

Ask a third party to proofread all your content. This is not the task of the designer or the original writer. It's best to bring in someone with a fresh perspective. Don't proofread your own work.


When you feel your website is almost ready for the public to see, it's time for beta testing — a process of going through all aspects of the site, making sure everything appears and functions as intended. Consider this checklist, at minimum:

  • Does the site look as intended in all targeted web browsers? Web browsers include the usual Internet Explorer, Firefox, Safari and Chrome, as well as those that come with common mobile devices. If you've been viewing the site on a desktop browser up until now, you may find unexpected glitches when you switch to a tablet or smartphone. This is the time to thoroughly review your site on a variety of devices before it can be considered ready for public consumption. Remember — your site's audience will use a wide range of devices to view your site, and it needs to work acceptably well on all of them. You don't have to physically test your site on every possible phone or tablet, but you should try it on a handful of common devices. Don't go out and buy a five-year-old Blackberry for testing purposes.
    "Emulation" websites and services like Spoon.net will generate previews of your site on just about every browser or device known to humankind, giving you a good idea of how it will look in most scenarios.
  • Interactive features work smoothly.
  • Contact or other forms work predictably and generate the correct response to the user and recipient of the information submitted.
  • Error messages are helpful and human-friendly.
  • Internal and external links function.
  • Images are sized properly.
  • All placeholder content has been replaced by the final copy/images, etc.
  • Internal and external links, including email links, work properly.
  • Integrations with third party software, such as email service providers, are working.

At this point its very wise to enlist someone who has had no involvement in the process to date, and ask them to methodically go through each page and feature in the site, noting any errors or glitches they find. Don't use someone who's been staring at the site for months. Problems to look out for could include typos, bad links, image sizing, failures on specific mobile devices, or content that's missing or incomplete. (Make sure to tell your tester that the design of the site is set in stone at this point, so they're not wasting time looking at non-content considerations.)

Pre-launch coordination

When you approach launch time, you'll need to coordinate with your company's other marketing efforts. If you're active on social media, write and proofread the announcement of your new/redesigned site, and set a schedule to post the announcement. Prepare to update your outgoing voicemail message and coordinate print advertising — everything needed to support the launch of the site.

Redirecting traffic from the "old" site

If your new website is replacing a previous version, it will probably have a different URL structure, and you need to map the old structure to the new. There are two reasons to do this. First, search engines have indexed the URLs of your old site. This indexing has a lot of value to people searching for what your company offers. When you launch a new site with different URLs, the old ones will break and users will get a "page not found" message (404 Error). You want to retain your hard-earned place in search engines. Second, site visitors may have bookmarked pages within your old site and want to return to them. If those pages' URLs change, you need to insure visitors still receive content that is relevant to their needs, instead of a page that no longer exists.

For example, your old site may have:

  • http://oursite.com/company/history.html
  • http://oursite.com/staff/california.html

while the new site has:

  • http://oursite.com/company-history
  • http://oursite.com/staff/california

The differences are subtle, but computers are very literal things — to the browser, the difference between "history.html" and "company-history.html" might as well be the distance between Mars and Earth. You need to go through the structure of the old site and make note of every page that has equivalent information in the new site and their URLs. If your old site has a lot of pages, you can use a tool like Powermapper to help automate the process. Sometimes old and new URLs will line up pretty well, like those above. Other times an old URL may not have an equivalent in the new site. This often happens if you've closed a division of your company, discontinued a project, or reorganized a department. Regardless of the reason, you'll still need exact URLs to work with for the next step. There are three ways to handle old URLs:

  • If they have an equivalent like the examples above, you can point the old URL to the new. To diverge in to the technical for a moment, this is done with a 301 Redirect, which tells search engines and users' web browsers that a URL has permanently changed. It looks like this: Redirect 301 /company/history.html http://oursite.com/company-history
  • If the links have no equivalent, you can send site visitors to a page which says "Sorry we can't find what you you're looking for. We've redesigned and reorganized our site, and some content has changed or moved." and provide a site map and search option.
  • You can also point all non-existent URLs right to the home page.

The larger the scale of your old site, the more work will be required to re-point old URLs. If you have analytics running on your old site, you may choose to re-point only the top 10 or 20 old URLs to new ones, and set a catch-all for all the rest, pointing them either to the "Sorry, we can't find what you're looking for…" page or the home page. Creating catch-all redirects, or those that match a specific URL pattern is a technical endeavor that we won't address here, but you can easily find information on .htaccess files (for Linux server) or web.config files (for NT server) at Stack Exchange or other resources.

Never launch on a Friday

It's never a good idea to launch a website, especially one on which many people depend, on a Friday or right before holidays. If something goes wrong, you may not have the resources to fix it when most of the office staff, vendors and other third parties who might be able to help have gone home for the weekend. Mondays are best for launching a new site, as that gives you the whole week to fix any unexpected problems that may arise, and plenty of support to help you do so.


Once you've thoroughly beta tested the site, it's time to launch. Specific steps vary by project, but generally this means either moving the site (files, database, configuration) from a development environment to a public one making it visible to the world, or simply updating server settings to allow visitors to yourcompany.com to see the new site.

Post-Launch Web statistics

Reviewing your website visitor statistics can give you vital insight in to how people are using your site. You'll need at least a month or two worth of data to make any determinations. Don't get too hung up on the pure numbers — all of them are approximate to one degree or another. Trends should be your main focus. Here are a few key points to consider:

  • Where are visitors coming from? Search engines, direct traffic (i.e., someone just typed your site's.
  • URL in to the browser), ads, links from other sites, etc.
  • Where do visitors live? Are they mostly local, regional, national, international?
  • What pages are the most popular?
  • How long are visitors staying on the site?
  • What is the bounce rate, that is how many users visit only one page on the site before leaving it entirely?

Google Analytics is among the most commonly used web statistics software and you will easily find answers to these questions in the high-level data it presents. Other web statistics software like KISSMetrics or Clicky should readily provide these answers as well.

Technical documentation

You'll also need detailed notes on how various parts of the site are implemented on the CMS. This is different from the documentation provided to the business. Much of your technical documentation will simply consist of the annotated elements discussed earlier in this document, including wireframes, style guide and Photoshop documents. Think about what information would be needed if you brought new people in to maintain the site, people who were not at all familiar with it. What do they require to pick up the project? They'll need:

  • Credentials for the CMS, web server, and other services connected to the site.
  • Written or video instructions on how to perform tasks in the CMS: adding news items, blog posts, swapping out photos — everything that someone can do to the site.
  • Recommended technical maintenance — how often do the CMS and other services require updating?
  • Notes on backups — what is being backed up, how often, and where is it backed up to?

Note: writing documentation of all kinds is one of a web professional's least favorite tasks, but it's very important. Don't slack on it. Think how terrible it would be to inherit a project without any technical documentation. Then use that dread as your inspiration! You don't want to leave anybody in a lurch down the line and doing this right will save time and frustration later on.


This is often overlooked by businesses and designers alike. Schedule regular backups of the site's files and database. Daily is ideal. Your hosting company may provide an automated way to do this, but if they don't, there are plenty of effective services and tools available to facilitate this process. That way, if your files or database get hacked, erased, corrupted or otherwise damaged, you can restore them with copies from the previous day.

Depending on the size of your site, frequency of updates and some technical matters that vary with each site, you may want to schedule more frequent backups. Ideally, your site will be backed up off-site, that is, in a different place than where it is hosted. Services like Amazon S3 or Rackspace Cloud are ideal for this purpose. The idea is that if your website gets irrevocably damaged, a recent copy is stored in a different physical location, allowing restoration of the site to the last undamaged version.

Maintenance plan

Your maintenance plan, which should have been budgeted for before you started, should clarify roles and responsibilities for every aspect of the site. For example, if two articles per week are to be posted, who is responsible for this, and who is that person's backup? If your site requires photos or graphics to be created regularly, make sure this work is assigned and understood by all involved. Determine who will check links, re-size images, write blog posts, etc. Write a simple maintenance plan and share it with everyone involved in the site's care and feeding. Remember, a good website isn't a one-time event, but rather an extensible communication tool that requires regular updates to remain valuable, relevant and compelling to site visitors.

Solicit visitor feedback

After it's been online for a while, a great way to improve the impact of your site is to solicit visitor feedback. There are a variety of ways to do this, from simple online surveys to on-site focus groups. Site visitors often have trouble articulating what they like and don't like about their experience. With this in mind, it's important to craft very clear and specific questions when soliciting feedback. And remember, if you're going to take a significant amount of visitors' time, offer something in return — a product discount, prize, or simply a handwritten note thanking them.


OK, one more time for posterity: A good website isn't a one-time event, but rather an extensible communications tool. Once you've built a great website, keep the momentum going. Devote resources to regular maintenance, and check in with your site visitors regularly to identify areas for improvement.

Recommended Reading
  • "Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability" by Steve Krug
    Helps readers understand the principles of intuitive navigation and information design.
  • "Content Strategy for Mobile" by Karen McGrane
    Making the case for a mobile strategy, publishing flexibly to multiple channels, and adapting your workflow to a world of emerging devices, platforms, screen sizes, and resolutions.
  • "Design Is A Job" by Mike Monteiro
    From contracts to selling design, from working with clients to working with each other, learn why navigating the business of design is just as important as the craft of it.
  • "Grow your SEO" by Candy Phelps
    A beginner's guide to SEO.
DEFINITIONS Term Definitions Adobe Flash A proprietary system for creating rich, interactive website features such as charts, graphs, animations and streaming video. The Flash player, that is, the browser add-on that allows users to via Flash content, is free. Flash authoring software is sold by Adobe. Beta testing The process of reviewing a website to ensure everything works as intended prior to launch. Content Management System (CMS) Software that provides website authoring, collaboration and administration tools designed to allow users with little knowledge of web programming languages or markup languages to create and manage the site's content with relative ease. Offers users the ability to manage documents and output for multiple author editing and participation. Popular CMS include WordPress, ExpressionEngine, Drupal, Joomla, Perch, Statamic, Craft, and hundreds more. Grid system A grid takes the available screen area and divides it up in to equal parts, for example, 10 columns of 96 pixels = 960 pixels. This makes layout and design easier. Many grid systems are available — use a search engine to see what's current. HTML Short for 'Hypertext Markup Language.' HTML is a tag-based language which defines the elements of content on a web page. For example, surrounding content in <p>...</p> tags creates a paragraph, while <strong>...</strong> creates bold text (adapted from Wikipedia). Javascript (JS) A programming language that runs inside a user's web browser, enhancing websites with a wide range of features such as mouseovers, slide shows, moving and fading elements, and more. Commonly implemented through a library like jQuery. CSS Short for 'Cascading Style Sheets.'' CSS is a set of instructions which define the layout and appearance of HTML elements. For example, CSS may specify that all paragraphs be 12 point Verdana, dark gray. Layout Deals with the arrangement of visual elements on a page. It generally involves organizational principles of composition to achieve specific communication objectives. Lorem Ipsum ("Greeking") Placeholder text used by web and graphic designers to fill space in mockups and incomplete web pages until real content is provided. May be as old as the sixteenth century. Meta tags Information about a web page (for example, title, description, author) that helps search engines and other resources understand the contents of that page. Responsive Web Design (RWD) A set of web design techniques that insure a site adjusts its presentation appropriately for different devices. Term originally coined by Ethan Marcotte. Search Engine Optimization (SEO) The process of affecting the visibility of a website in a search engine's results. URL Stands for Uniform Resource Locator, that is, a unique address on the web that contains specific content. For example, tastyfruit.com/citrus/oranges Wireframe A visual representation of the layout elements of a web page, intended to show page structure, element placement and sizing. (vf, ra, yk, il)
Categories: Web Design

How To Prevent Common WordPress Theme Mistakes

Smashing Magazine - Mon, 03/05/2018 - 03:25
If you’ve been thinking of creating free or premium WordPress themes, well, I hope I can help you avoid some of the mistakes I’ve made over the years. Even though I always strive for good clean code, there are pursuits that still somehow lead me into making mistakes. I hope that I can help you avoid them with the help of this article. 1. Don’t Gradually Reinvent The Wheel Be careful when making things look nice — especially if you create a function that does almost exactly the same thing as another function just to wrap things nicely.
Categories: Web Design

12 Best Magazine Themes for WordPress Websites

WordPress is an excellent platform to build your online magazine site on top of. There are hundreds of high-quality magazine themes out there that come with all the features...

The post 12 Best Magazine Themes for WordPress Websites appeared first on Onextrapixel.

Categories: Web Design

Beyond Tools: How Building A Design System Can Improve How You Work

Smashing Magazine - Fri, 03/02/2018 - 06:00
When high potential projects fall apart, it’s often a failure of collaboration and alignment. The tools, the assumptions, the opportunity, and the intentions may line up, but if people don’t communicate or don’t have a clear map to help them move in the same direction, even the best projects falter. Communication failures are human problems, so they’re messy and hard to solve. They involve feelings and a willingness to have uncomfortable conversations.
Categories: Web Design

A Comprehensive Guide To Wireframing And Prototyping

Smashing Magazine - Thu, 03/01/2018 - 08:45
(This is a sponsored article.) With the big picture established and your user interface considered, it’s time to start building some prototypes. My sixth article in this series of ten articles dives into the prototyping process. As I’ve stressed before in the earlier articles in this series, the best design follows an iterative process: You undertake research, working with users to identify the underlying user requirements that need to be addressed.
Categories: Web Design

Contributing To WordPress: A Beginner’s Guide For Non-Coders

Smashing Magazine - Thu, 03/01/2018 - 04:50
If you’ve been using WordPress for any amount of time, there’s a good chance you’ve come across the following statement: “Free as in speech, not free as in beer.’ If you haven’t, pull up a chair and let’s talk. WordPress is a free and open-source software (also known as FOSS) project. The explanation of that could easily fill up a separate article, but the TL;DR version is that the software is free to download, use, inspect and modify by anyone who has a copy of it.
Categories: Web Design

11 Free User Polling & Voting Plugins For WordPress

Gathering user feedback is super important on the web. You can gather feedback through quizzes, emails, or even polls with Q&As embedded right into your site. In the past...

The post 11 Free User Polling & Voting Plugins For WordPress appeared first on Onextrapixel.

Categories: Web Design

Exploring New Worlds In March: The Smashing Creativity Submissions And Winner

Smashing Magazine - Wed, 02/28/2018 - 06:30
Everybody’s an artist. That was the idea behind the Smashing Creativity Challenge which we announced at the beginning of the month. We asked the community to get their creative ideas flowing, and design a desktop wallpaper for March 2018. The only requirement: The wallpaper had to somehow relate to the theme “Exploring New Worlds”. How? Well, only your imagination was the limit. Today, we are happy to present the result of this creative experiment, and the lucky winner, too, of course.
Categories: Web Design

A Gentle Introduction to Higher-Order Components in React: Best Practices

Tuts+ Code - Web Development - Wed, 02/28/2018 - 04:00

This is the third part of the series on Higher-Order Components. In the first tutorial, we started from ground zero. We learned the basics of ES6 syntax, higher-order functions, and higher-order components. 

The higher-order component pattern is useful for creating abstract components—you can use them to share data (state and behavior) with your existing components. In the second part of the series, I demonstrated practical examples of code using this pattern. This includes protected routes, creating a configurable generic container, attaching a loading indicator to a component, etc. 

In this tutorial, we will have a look at some best practices and dos and don'ts that you should look into while writing HOCs. 


React previously had something called Mixins, which worked great with the React.createClass method. Mixins allowed developers to share code between components. However, they had some drawbacks, and the idea was dropped eventually. Mixins were not upgraded to support ES6 classes, and Dan Abramov even wrote an in-depth post on why Mixins are considered harmful.

Higher-order components emerged as an alternative to Mixins, and they supported ES6 classes. Moreover, HOCs don't have to do anything with the React API and are a generic pattern that works well with React. However, HOCs have flaws too. Although the downsides of higher-order components might not be evident in smaller projects, you could have multiple higher-order components chained to a single component, just like below.

const SomeNewComponent = withRouter(RequireAuth(LoaderDemo(GenericContainer(CustomForm(Form)))))

You shouldn't let the chaining get to the point where you are asking yourself the question: "Where did that props come from?" This tutorial addresses some of the common issues with higher-order component patterns and the solutions to get them right. 

The Problems With HOC

Some of the common problems concerned with HOCs have less to do with HOCs themselves, but rather your implementation of them. 

As you already know, HOCs are great for code abstraction and creating reusable code. However, when you have multiple HOCs stacked up, and if something looks out of place or if some props are not showing up, it's painful to debug because the React DevTools give you a very limited clue about what might have gone wrong. 

A Real-World HOC Problem

To understand the drawbacks of HOCs, I've created an example demo that nests some of the HOCs that we created in the previous tutorial. We have four higher-order functions wrapping that single ContactList component. If the code doesn't make sense or if you haven't followed my previous tutorial, here is a brief summary of how it works.

withRouter is a HOC that's part of the react-router package. It provides you access to the history object's properties and then passes them as a prop. 

withAuth looks for an authentication prop and, if authentication is true, it renders the WrappedComponent. If authentication is false, it pushes '/login' to the history object.

withGenericContainer accepts an object as an input in addition to the WrappedComponent. The GenericContainer makes API calls and stores the result in the state and then sends the data to the wrapped component as props.

withLoader is a HOC that attaches a loading indicator. The indicator spins until the fetched data reaches the state.

BestPracticeDemo.jsx class BestPracticesDemo extends Component { render() { return( <div className="contactApp"> <ExtendedContactList authenticated = {true} {...this.props} contacts ="this" /> </div> ) } } const ContactList = ({contacts}) => { return( <div> <ul> {contacts.map( (contact) => <li key={contact.email}> <img src={contact.photo} width="100px" height="100px" alt="presentation" /> <div className="contactData"> <h4>{contact.name}</h4> <small>{contact.email}</small> <br/><small> {contact.phone}</small> </div> </li> )} </ul> </div> ) } const reqAPI = {reqUrl: 'https://demo1443058.mockable.io/users/', reqMethod:'GET', resName:'contacts'} const ExtendedContactList = withRouter( withAuth( withGenericContainer(reqAPI)( withLoader('contacts') (ContactList)))); export default BestPracticesDemo;

Now you can see for yourself some of the common pitfalls of higher-order components. Let's discuss some of them in detail.

Basic Dos and Don'tsDon't Forget to Spread the Props in Your HOC

Assume that we have an authenticated = { this.state.authenticated } prop at the top of the composition hierarchy. We know that this is an important prop and that this should make it all the way to the presentational component. However, imagine that an intermediate HOC, such as withGenericContainer, decided to ignore all its props. 

//render method of withGenericContainer render() { return( <WrappedComponent /> ) }

This is a very common mistake that you should try to avoid while writing higher-order components. Someone who isn't acquainted with HOCs might find it hard to figure out why all the props are missing because it would be hard to isolate the problem. So, always remember to spread the props in your HOC.

//The right way render() { return( <WrappedComponent {...this.props} {...this.state} />) }Don't Pass Down Props That Have No Existence Beyond the Scope of the HOC

A HOC might introduce new props that the WrappedComponent might not have any use for. In such cases, it's a good practice to pass down props that are only relevant to the composed components. 

A higher-order component can accept data in two ways: either as the function's argument or as the component's prop. For instance, authenticated = { this.state.authenticated } is an example of a prop, whereas in withGenericContainer(reqAPI)(ContactList), we are passing the data as arguments.  

Because withGenericContainer is a function, you can pass in as few or as many arguments as you like. In the example above, a config object is used to specify a component's data dependency. However, the contract between an enhanced component and the wrapped component is strictly through props. 

So I recommend filling in the static-time data dependencies via the function parameters and passing dynamic data as props. The authenticated props are dynamic because a user can be either authenticated or not depending on whether they are logged in or not, but we can be sure that the contents of the reqAPI object are not going to change dynamically. 

Don’t Use HOCs Inside the Render Method

Here is an example that you should avoid at all cost.

var OriginalComponent = () => <p>Hello world.</p>; class App extends React.Component { render() { return React.createElement(enhanceComponent(OriginalComponent)); } };

Apart from the performance hitches, you will lose the state of the OriginalComponent and all of its children on each render. To solve this problem, move the HOC declaration outside the render method so that it is only created once, so that the render always returns the same EnhancedComponent.

var OriginalComponent = () => <p>Hello world.</p>; var EnhancedComponent = enhanceComponent(OriginalComponent); class App extends React.Component { render() { return React.createElement(EnhancedComponent); } };Don't Mutate the Wrapped Component

Mutating the Wrapped Component inside a HOC makes it impossible to use the Wrapped Component outside the HOC. If your HOC returns a WrappedComponent, you can almost always be sure that you're doing it wrong. The example below demonstrates the difference between mutation and composition.

function logger(WrappedComponent) { WrappedComponent.prototype.componentWillReceiveProps = function(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); }; // We're returning the WrappedComponent rather than composing //it return WrappedComponent; }

Composition is one of React's fundamental characteristics. You can have a component wrapped inside another component in its render function, and that's what you call composition. 

function logger(WrappedComponent) { return class extends Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { // Wraps the input component in a container, without mutating it. Good! return <WrappedComponent {...this.props} />; } } }

Moreover, if you mutate the WrappedComponent inside a HOC and then wrap the enhanced component using another HOC, the changes made by the first HOC will be overridden. To avoid such scenarios, you should stick to composing components rather than mutating them.

Namespace Generic Propnames

The importance of namespacing prop names is evident when you have multiple stacked up. A component might push a prop name into the WrappedComponent that's already been used by another higher-order component. 

import React, { Component } from 'react'; const withMouse = (WrappedComponent) => { return class withMouse extends Component { constructor(props) { super(props); this.state = { name: 'Mouse' } } render() { return( <WrappedComponent {...this.props} name={this.state.name} /> ); } } } const withCat = (WrappedComponent) => { return class withCat extends Component { render() { return( <WrappedComponent {...this.props} name= "Cat" /> ) } } } const NameComponent = ({name}) => { return( <div> {name} </div>) } const App =() => { const EnhancedComponent = withMouse(withCat(NameComponent)); return( <div> <EnhancedComponent /> </div>) } export default App;

Both the withMouse and withCat are trying to push their own version of name prop. What if the EnhancedComponent too had to share some props with the same name?

<EnhancedComponent name="This is important" />

Wouldn't it be a source of confusion and misdirection for the end developer? The React Devtools don't report any name conflicts, and you will have to look into the HOC implementation details to understand what went wrong. 

This can be solved by making HOC prop names scoped as a convention via the HOC that provides them. So you would have withCat_name and withMouse_name instead of a generic prop name. 

Another interesting thing to note here is that ordering your properties is important in React. When you have the same property multiple times, resulting in a name conflict, the last declaration will always survive. In the above example, the Cat wins since it's placed after { ...this.props }. 

If you would prefer to resolve the name conflict some other way, you can reorder the properties and spread this.props last. This way, you can set sensible defaults that suit your project.

Make Debugging Easier Using a Meaningful Display Name

The components created by a HOC show up in the React Devtools as normal components. It's hard to distinguish between the two. You can ease the debugging by providing a meaningful displayName for the higher-order component. Wouldn't it be sensible to have something like this on React Devtools?

<withMouse(withCat(NameComponent)) > ... </withMouse(withCat(NameComponent))>

So what is displayName? Each component has a displayName property that you can use for debugging purposes. The most popular technique is to wrap the display name of the WrappedComponent. If withCat is the HOC, and NameComponent is the WrappedComponent, then the displayName will be withCat(NameComponent). 

const withMouse = (WrappedComponent) => { class withMouse extends Component { /* */ } withMouse.displayName = `withMouse(${getDisplayName(WrappedComponent)})`; return withMouse; } const withCat = (WrappedComponent) => { class withCat extends Component { /* */ } withCat.displayName = `withCat(${getDisplayName(WrappedComponent)})`; return withCat; } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } An Alternative to Higher-Order Components

Although Mixins are gone, it would be misleading to say higher-order components are the only pattern out there that allow code sharing and abstraction. Another alternative pattern has emerged, and I've heard some say it's better than HOCs. It's beyond the scope of this tutorial to touch on the concept in depth, but I will introduce you to render props and some basic examples that demonstrate why they are useful. 

Render props are referred to by a number of different names:

  • render prop
  • children prop
  • function as a child
  • render callback

Here is a quick example that should explain how a render prop works.

class Mouse extends Component { constructor() { super(); this.state = { name: "Nibbles" } } render() { return( <div> {this.props.children(this.state)} </div> ) } } class App extends Component { render() { return( <Mouse> {(mouse) => <div> The name of the mouse is {mouse.name} </div> } </Mouse> ) } }

As you can see, we've got rid of the higher-order functions. We have a regular component called Mouse. Instead of rendering a wrapped component in its render method, we are going to render this.props.children() and pass in the state as an argument. So we are giving Mouse a render prop, and the render prop decides what should be rendered.

In other words, the Mouse components accept a function as the value for the children props. When Mouse renders, it returns the state of the Mouse, and the render prop function can use it however it pleases. 

There are a few things I like about this pattern:

  • From a readability perspective, it's more evident where a prop is coming from.
  • This pattern is dynamic and flexible. HOCs are composed at static-time. Although I've never found that to be a limitation, render props are dynamically composed and are more flexible. 
  • Simplified component composition. You could say goodbye to nesting multiple HOCs.

Higher-order components are patterns that you can use to build robust, reusable components in React. If you're going to use HOCs, there are a few ground rules that you should follow. This is so that you don't regret the decision of using them later on. I've summarized most of the best practices in this tutorial. 

HOCs are not the only patterns that are popular today. Towards the end of the tutorial, I've introduced you to another pattern called render props that is gaining ground among React developers. 

I won't judge a pattern and say that this one is better than another. As React grows, and the ecosystem that surrounds it matures, more and more patterns will emerge. In my opinion, you should learn them all and stick with the one that suits your style and that you're comfortable with.

This also marks the end of the tutorial series on higher-order components. We've gone from ground zero to mastering an advanced technique called HOC. If I missed anything or if you have suggestions/thoughts, I would love to hear them. You can post them in the comments. 

Categories: Web Design

Challenge: Build a React Component

Tuts+ Code - Web Development - Wed, 02/28/2018 - 02:17

The best way to learn a new skill is by putting it into practice. So here's a challenge for you.

In this video from my course, Modern Web Apps With React and Redux, you'll be challenged to create a React Component for displaying a Twitter avatar. You can try solving it on your own (with a hint), or you can let me walk you through the solution.

Challenge: Build a React Component The Challenge

In this challenge, you need to build a React component for displaying a Twitter avatar. As you can see from the CodePen below, it just takes props.handle and prints out a little URL in an image tag. Very simple. 

What we need to do is write a profile component that uses a Twitter avatar component to show the image and the name. You can see the ReactDOM.render call for some hints.

If you'd like to try this challenge on your own, go ahead! Otherwise, read on as I walk you through the solution.

The Solution

Start by forking the pen so that you can build our own component, and then rename it by adding "MY SOLUTION". 

In our ReactDOM call, we have a Profile component that we're calling, and we give it a name and a handle.

So this should be pretty straightforward. Let's go ahead and create a profile. I'm going to do this as a stateless component, just using a JavaScript function. If you want, you can actually use React.createClass, or the class syntax itself. Do whatever you like. But I like using stateless functions as much as possible.

This is going to take one parameter, which is our props object, but it's going to have name and handle properties. So let's go ahead and destructure that.

const Profile = ({ name, handle }) =>

Then let's return a div. And inside this div, let's return an h1 with the name for this specific account. And underneath this, we will have a TwitterAvatar, which requires a handle property. So we will pass it a handle, which will be equal to the handle we have. 

const Profile = ({ name, handle }) => <div> <h1> { name } </h1> <TwitterAvatar handle={handle} /> </div>;

There we go. It should be that simple. So save this in CodePen, and you can see that we get ReactJS and we get the Twitter avatar. 

Let's go ahead and change the name to Tuts+ and the Twitter handle to tutsplus, and you can see that it updates.

So, as you can see, we can change this to different names and Twitter avatars, and we can see this in action. Good job! You have built a very basic React component. It's a good place to start in seeing how you can create components and use their properties, and also how you can pass those properties on to other components, to do some of the work for you.

Here's the final pen showing the solution in full:

Watch the Full Course

React is a JavaScript library for building user interfaces that has taken the web development world by storm, and Redux is a great way of managing application state. In the full course, Modern Web Apps With React and Redux, you'll learn all about how React, Redux and other leading modules fit together for a complete picture of app development.

It's a comprehensive, four-hour course with 35 video lessons, and I'll take you through the process of using these two libraries to build a complete web application from scratch. You'll start with the simplest possible architecture and slowly build up the app, feature by feature. By the end, you'll have created a complete flashcards app for learning by spaced repetition.

You can take this course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 440,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Categories: Web Design

Smashing Newsletter #200: The Things We Learned

Smashing Magazine - Tue, 02/27/2018 - 07:40
When we share our lessons learned, we can’t predict who is going to read them, but it can make all the difference in the world. I still vividly remember that day when I received an email from a school teacher in Johannesburg, South Africa, five or six years ago. Back then, they didn’t have any teaching materials available at their school, and interaction design was often taught on paper with a few outdated books from the 90s.
Categories: Web Design

Use These Web Design Tricks to Grow Your Business Exponentially

Entrepreneur: Latest Web Design Articles - Tue, 02/27/2018 - 07:30
An improved user experience will make your site more trustworthy.
Categories: Web Design

Eloquent Mutators and Accessors in Laravel

Tuts+ Code - Web Development - Tue, 02/27/2018 - 05:00

In this article, we'll go through mutators and accessors of the Eloquent ORM in the Laravel web framework. After the introduction, we'll go through a handful of examples to understand these concepts.

In Laravel, mutators and accessors allow you to alter data before it's saved to and fetched from a database. To be specific, the mutator allows you to alter data before it's saved to a database. On the other hand, the accessor allows you to alter data after it's fetched from a database.

In fact, the Laravel model is the central place where you can create mutator and accessor methods. And of course, it's nice to have all your modifications in a single place rather than scattered over different places.

Create Accessors and Mutators in a Model Class

As you're familiar with the basic concept of mutators and accessors now, we'll go ahead and develop a real-world example to demonstrate it.

I assume that you're aware of the Eloquent model in Laravel, and we'll use the Post model as a starting point of our example. If you haven't created the Post model yet, let's use the artisan command to create it.

php artisan make:model Post --migration

That should create a model file at app/Post.php as shown below.

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // }

Let's replace the contents of that file with the following.

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'created_at', 'updated_at', 'published_at' ]; /** * Get the post title. * * @param string $value * @return string */ public function getNameAttribute($value) { return ucfirst($value); } /** * Set the post title. * * @param string $value * @return string */ public function setNameAttribute($value) { $this->attributes['name'] = strtolower($value); } }

As we've used the --migration option, it should also create an associated database migration. Just in case you are not aware, you can run the following command so that it actually creates a table in the database.

php artisan migrate

In order to run examples in this article, you need to create name and published_at columns in the post table. Anyway, we won't go into the details of the migration topic, as it's out of the scope of this article. So we'll get back to methods that we are interested in.

Firstly, let's go through the mutator method.

/** * Set the post title. * * @param string $value * @return string */ public function setNameAttribute($value) { $this->attributes['name'] = strtolower($value); }

As we discussed earlier, the mutators are used to alter data before it's saved to a database. As you can see, the syntax of the mutator method is set{attribute-name}Attribute. Of course, you need to replace {attribute-name} with an actual attribute name.

The setNameAttribute method is called before the value of the name attribute is saved in the database. To keep things simple, we've just used the strtolower function that converts the post title to lowercase before it's saved to the database.

In this way, you could create mutator methods on all columns of your table. Next, let's go through the accessor method.

If mutators are used to alter data before it's saved to a database, the accessor method is used to alter data after it's fetched from a database. The syntax of the accessor method is the same as that of the mutator except that it begins with the get keyword instead of the set keyword.

Let's go through the accessor method getNameAttribute.

/** * Get the post title. * * @param string $value * @return string */ public function getNameAttribute($value) { return ucfirst($value); }

The getNameAttribute method will be called after the value of the name attribute is fetched from the database. In our case, we've just used the ucfirst method to alter the post title.

And that's the way you are supposed to use accessors in your models. So far, we've just created mutator and accessor methods, and we'll test those in the upcoming section.

Mutators in Action

Let's create a controller at app/Http/Controllers/MutatorController.php so that we can test the mutator method that we created in the earlier section.

<?php // app/Http/Controllers/MutatorController.php namespace App\Http\Controllers; use App\Post; use App\Http\Controllers\Controller; class MutatorController extends Controller { public function index() { // create a new post object $post = new Post; $post->setAttribute('name', 'Post title'); $post->save(); } }

Also, you need to create an associated route in the routes/web.php file to access it.

Route::get('mutator/index', 'MutatorController@index');

In the index method, we're creating a new post using the Post model. It should set the value of the name column to post title as we've used the strtolower function in the setNameAttribute mutator method.

Date Mutators

In addition to the mutator we discussed earlier, the Eloquent model provides a couple of special mutators that allow you to alter data. For example, the Eloquent model in Laravel comes with a special $dates property that allows you to automatically convert the desired columns to a Carbon date instance.

In the beginning of this article, we created the Post model, and the following code was part of that class.

... ... /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'created_at', 'updated_at', 'published_at' ]; ... ...

As you probably know, Laravel always creates two date-related fields, created_at and updated_at, with each database migration. And it converts those values to a Carbon date instance as well.

Let's assume that you have a couple of fields in a table that you would like to treat as date fields. In that case, you just need to add column names in the $dates array.

As you can see in the above code, we've added the published_at column in the $dates array, and it makes sure that the value of that column will be converted to a Carbon date instance.

Accessors in Action

To see accessors in action, let's go ahead and create a controller file app/Http/Controllers/AccessorController.php with the following contents.

<?php namespace App\Http\Controllers; use App\Post; use App\Http\Controllers\Controller; class AccessorController extends Controller { public function index() { // load post $post = Post::find(1); // check the name property echo $post->name; // check the date property echo $post->published_at; // as we've mutated the published_at column as Carbon date, we can use following as well echo $post->published_at->getTimestamp(); exit; } }

Also, let's create an associated route in the routes/web.php file to access it.

Route::get('accessor/index', 'AccessorController@index');

In the index method, we've used the Post model to load an example post in the first place.

Next, we're inspecting the value of the name column, and it should start with an uppercase letter as we've already defined the accessor method getNameAttribute for that column.

Moving further, we've inspected the value of the published_at column, and that should be treated as a date. Due to that, Laravel converts it to a Carbon instance so that you can use all the utility methods provided by that library. In our case, we've used the getTimestamp method to convert the date into a timestamp.

And that brings us to the end of this article!


Today, we've explored the concepts of mutators and accessors of the Eloquent ORM in Laravel. It provides a nice way to alter data before it's saved to and fetched from a database.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Don't hesitate to share your thoughts using the feed below!

Categories: Web Design

A Gentle Introduction to HOC in React: Learn by Example

Tuts+ Code - Web Development - Tue, 02/27/2018 - 04:00

This is the second part of the series on Higher-Order Components (HOCs). Today, I will cover different higher-order component patterns that are useful and implementable. With HOCs, you can abstract redundant code into a layer of higher order. However, like any other patterns out there, it will take some time to get used to HOCs. This tutorial will help you bridge that gap. 


I recommend that you follow the first part of the series if you haven't already. In the first part, we talked about HOC syntax basics and everything you need to get started with higher-order components.

In this tutorial, we will be building on top of the concepts that we've already covered in part one. I've created several sample HOCs which are practically useful, and you can incorporate these ideas into your project. Code snippets are provided in each section, and a working demo of all the practical HOCs discussed in this tutorial is provided at the end of the tutorial.

You can also fork the code from my GitHub repo.

Practical Higher-Order Components

Since HOCs create a new abstract container component, here is the list of things that you can normally do with them:

  • Wrap an element or component around a component.
  • State abstraction.
  • Manipulate props, e.g. adding new props and modifying or removing existing props.
  • Props validation to create.
  • Use refs to access instance methods.

Let's talk about these one by one. 

HOC as a Wrapper Component

If you recall, the final example in my previous tutorial demonstrated how a HOC wraps the InputComponent with other components and elements. This is useful for styling and for reusing logic wherever possible. For instance, you can use this technique to create a reusable loader indicator or an animated transition effect that should be triggered by certain events. 

A Loading Indicator HOC

The first example is a loading indicator built using HOC. It checks whether a particular prop is empty, and the loading indicator is displayed until the data is fetched and returned.

LoadIndicator/LoadIndicatorHOC.jsx/* Method that checks whether a props is empty prop can be an object, string or an array */ const isEmpty = (prop) => ( prop === null || prop === undefined || (prop.hasOwnProperty('length') && prop.length === 0) || (prop.constructor === Object && Object.keys(prop).length === 0) ); const withLoader = (loadingProp) => (WrappedComponent) => { return class LoadIndicator extends Component { render() { return isEmpty(this.props[loadingProp]) ? <div className="loader" /> : <WrappedComponent {...this.props} />; } } } export default withLoader;LoadIndicator/LoadIndicatorDemo.jsximport React, { Component } from 'react'; import withLoader from './LoaderHOC.jsx'; class LoaderDemo extends Component { constructor(props) { super(props); this.state = { contactList: [] } } componentWillMount() { let init = { method: 'GET', headers: new Headers(), mode: 'cors', cache: 'default' }; fetch ('https://demo1443058.mockable.io/users/', init) .then( (response) => (response.json())) .then( (data) => this.setState( prevState => ({ contactList: [...data.contacts] }) ) ) } render() { return( <div className="contactApp"> <ContactListWithLoadIndicator contacts = {this.state.contactList} /> </div> ) } } const ContactList = ({contacts}) => { return( <ul> {/* Code omitted for brevity */} </ul> ) } /* Static props can be passed down as function arguments */ const ContactListWithLoadIndicator = withLoader('contacts')(ContactList); export default LoaderDemo;

This is also the first time that we've used the second parameter as input to the HOC. The second parameter, which I've named 'loadingProp', is used here to tell the HOC that it needs to check whether that particular prop is fetched and available. In the example, the isEmpty function checks whether the loadingProp is empty, and an indicator is displayed until the props are updated.

You have two options for passing down data to the HOC, either as a prop (which is the usual way) or as a parameter to the HOC.

/* Two ways of passing down props */ <ContactListWithLoadIndicator contacts = {this.state.contactList} loadingProp= "contacts" /> //vs const ContactListWithLoadIndicator = withLoader('contacts')(ContactList);

Here is how I choose between the two. If the data doesn't have any scope beyond that of the HOC and if the data is static, then pass them as parameters. If the props are relevant to the HOC and also to the wrapped component, pass them as usual props. I've covered more about this in my third tutorial.

State Abstraction and Prop Manipulation

State abstraction means generalizing the state to a higher-order component. All the state management of the WrappedComponent will be handled by the higher-order component. The HOC adds new state, and then the state is passed down as props to the WrappedComponent. 

A Higher-Order Generic Container

If you noticed, the loader example above had a component that made a GET request using the fetch API. After retrieving the data, it was stored in the state. Making an API request when a component mounts is a common scenario, and we could make a HOC that perfectly fits into this role.

GenericContainer/GenericContainerHOC.jsximport React, { Component } from 'react'; const withGenericContainer = ({reqUrl, reqMethod, resName}) => WrappedComponent => { return class GenericContainer extends Component { constructor(props) { super(props); this.state = { [resName]: [], } } componentWillMount() { let init = { method: reqMethod, headers: new Headers(), mode: 'cors', cache: 'default' }; fetch(reqUrl, init) .then( (response) => (response.json())) .then( (data) => {this.setState( prevState => ({ [resName]: [...data.contacts] }) )} ) } render() { return( <WrappedComponent {...this.props} {...this.state} />) } } } export default withGenericContainer;GenericContainer/GenericContainerDemo.jsx/* A presentational component */ const GenericContainerDemo = () => { return ( <div className="contactApp"> <ContactListWithGenericContainer /> </div> ) } const ContactList = ({contacts}) => { return( <ul> {/* Code omitted for brevity */} </ul> ) } /* withGenericContainer HOC that accepts a static configuration object. The resName corresponds to the name of the state where the fetched data will be stored*/ const ContactListWithGenericContainer = withGenericContainer( { reqUrl: 'https://demo1443058.mockable.io/users/', reqMethod: 'GET', resName: 'contacts' })(ContactList);

The state has been generalized, and the value of the state is being passed down as props. We've made the component configurable too.

const withGenericContainer = ({reqUrl, reqMethod, resName}) => WrappedComponent => { }

It accepts a configuration object as an input that gives more information about the API URL, the method, and the name of the state key where the result is stored. The logic used in componentWillMount() demonstrates using a dynamic key name with this.setState.

A Higher-Order Form

Here is another example that uses the state abstraction to create a useful higher-order form component. 

CustomForm/CustomFormDemo.jsxconst Form = (props) => { const handleSubmit = (e) => { e.preventDefault(); props.onSubmit(); } const handleChange = (e) => { const inputName = e.target.name; const inputValue = e.target.value; props.onChange(inputName,inputValue); } return( <div> {/* onSubmit and onChange events are triggered by the form */ } <form onSubmit = {handleSubmit} onChange={handleChange}> <input name = "name" type= "text" /> <input name ="email" type="text" /> <button type="submit"> Submit </button> </form> </div> ) } const CustomFormDemo = (props) => { return( <div> <SignupWithCustomForm {...props} /> </div> ); } const SignupWithCustomForm = withCustomForm({ contact: {name: '', email: ''}})({propName:'contact', propListName: 'contactList'})(Form); CustomForm/CustomFormHOC.jsxconst CustomForm = (propState) => ({propName, propListName}) => WrappedComponent => { return class withCustomForm extends Component { constructor(props) { super(props); propState[propListName] = []; this.state = propState; this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); } /* prevState holds the old state. The old list is concatenated with the new state and copied to the array */ handleSubmit() { this.setState( prevState => { return ({ [propListName]: [...prevState[propListName], this.state[propName] ] })}, () => console.log(this.state[propListName]) )} /* When the input field value is changed, the [propName] is updated */ handleChange(name, value) { this.setState( prevState => ( {[propName]: {...prevState[propName], [name]:value} }) ) } render() { return( <WrappedComponent {...this.props} {...this.state} onChange = {this.handleChange} onSubmit = {this.handleSubmit} /> ) } } } export default withCustomForm;

The example demonstrates how the state abstraction can be used along with a presentational component to make form creation easier. Here, the form is a presentational component and is an input to the HOC. The initial state of the form and the name of the state items are also passed as parameters. 

const SignupWithCustomForm = withCustomForm ({ contact: {name: '', email: ''}}) //Initial state ({propName:'contact', propListName: 'contactList'}) //The name of state object and the array (Form); // WrappedComponent

However, note that if there are multiple props with the same name, ordering is important, and the last declaration of a prop will always win. In this case, if another component pushes a prop named contact or contactList, that will result in a name conflict. So you should either namespace your HOC props so that they don't conflict with the existing props or order them in such a way that the props that should have the highest priority are declared first. This will be covered in depth in the third tutorial.

Prop Manipulation Using HOC

Prop manipulation involves adding new props, modifying existing props, or ignoring them entirely. In the CustomForm example above, the HOC passed down some new props.

<WrappedComponent {...this.props} {...this.state} onChange = {this.handleChange} onSubmit = {this.handleSubmit} />

Similarly, you can decide to disregard props entirely. The example below demonstrates this scenario.

// Technically an HOC const ignoreHOC = (anything) => (props) => <h1> The props are ignored</h1> const IgnoreList = ignoreHOC(List)() <IgnoreList />

You can also do some validation/filtering props using this technique. The higher-order component decides whether a child component should receive certain props, or route the user to a different component if certain conditions are not met. 

A Higher-Order Component for Protecting Routes

 Here is an example of protecting routes by wrapping the relevant component with a withAuth higher-order component.

ProtectedRoutes/ProtectedRoutesHOC.jsxconst withAuth = WrappedComponent => { return class ProtectedRoutes extends Component { /* Checks whether the used is authenticated on Mount*/ componentWillMount() { if (!this.props.authenticated) { this.props.history.push('/login'); } } render() { return ( <div> <WrappedComponent {...this.props} /> </div> ) } } } export default withAuth;ProtectedRoutes/ProtectedRoutesDemo.jsximport {withRouter} from "react-router-dom"; class ProtectedRoutesDemo extends Component { constructor(props) { super(props); /* Initialize state to false */ this.state = { authenticated: false, } } render() { const { match } = this.props; console.log(match); return ( <div> <ul className="nav navbar-nav"> <li><Link to={`${match.url}/home/`}>Home</Link></li> <li><Link to={`${match.url}/contacts`}>Contacts(Protected Route)</Link></li> </ul> <Switch> <Route exact path={`${match.path}/home/`} component={Home} /> <Route path={`${match.path}/contacts`} render={() => <ContactsWithAuth authenticated={this.state.authenticated} {...this.props} />} /> </Switch> </div> ); } } const Home = () => { return (<div> Navigating to the protected route gets redirected to /login </div>); } const Contacts = () => { return (<div> Contacts </div>); } const ContactsWithAuth = withRouter(withAuth(Contacts)); export default ProtectedRoutesDemo;

withAuth checks if the user is authenticated, and if not, redirects the user to /login. We've used withRouter, which is a react-router entity. Interestingly, withRouter is also a higher-order component that is used to pass the updated match, location, and history props to the wrapped component every time it renders. 

For instance, it pushes the history object as props so that we can access that instance of the object as follows:


You can read more about withRouter in the official react-router documentation.

Accessing the Instance via Refs

React has a special attribute that you can attach to a component or an element. The ref attribute (ref stands for reference) can be a callback function attached to a component declaration.

The callback gets invoked after the component is mounted, and you get an instance of the referenced component as the callback's parameter. If you are not sure about how refs work, the official documentation on Refs and the DOM talks about it in depth.

In our HOC, the benefit of using ref is that you can get an instance of the WrappedComponent and call its methods from the higher-order component. This is not part of the typical React dataflow because React prefers communication via props. However, there are many places where you might find this approach beneficial. 

RefsDemo/RefsHOC.jsxconst withRefs = WrappedComponent => { return class Refs extends Component { constructor(props) { super(props); this.state = { value: '' } this.setStateFromInstance = this.setStateFromInstance.bind(this); } /* This method calls the Wrapped component instance method getCurrentState */ setStateFromInstance() { this.setState({ value: this.instance.getCurrentState() }) } render() { return( <div> { /* The ref callback attribute is used to save a reference to the Wrapped component instance */ } <WrappedComponent {...this.props} ref= { (instance) => this.instance = instance } /> <button onClick = {this. setStateFromInstance }> Submit </button> <h3> The value is {this.state.value} </h3> </div> ); } } }RefsDemo/RefsDemo.jsxconst RefsDemo = () => { return (<div className="contactApp"> <RefsComponent /> </div> ) } /* A typical form component */ class SampleFormComponent extends Component { constructor(props) { super(props); this.state = { value: '' } this.handleChange = this.handleChange.bind(this); } getCurrentState() { console.log(this.state.value) return this.state.value; } handleChange(e) { this.setState({ value: e.target.value }) } render() { return ( <input type="text" onChange={this.handleChange} /> ) } } const RefsComponent = withRefs(SampleFormComponent);

The ref callback attribute saves a reference to the WrappedComponent.

<WrappedComponent {...this.props} ref= { (instance) => this.instance = instance } />

this.instance has a reference to the WrappedComponent. You can now call the instance's method to communicate data between components. However, use this sparingly and only if necessary. 

Final Demo

I've incorporated all the examples in this tutorial into a single demo that you can use below. 


This is the end of the second tutorial on higher-order components. We learned a lot today about different HOC patterns and techniques, and went through practical examples that demonstrated how we could use them in our projects.

In the third part of the tutorial, you can look forward to some best practices and HOC alternatives that you should know of. Stay tuned until then. Share your thoughts in the comment box.

Categories: Web Design

How GDPR Will Change The Way You Develop

Smashing Magazine - Tue, 02/27/2018 - 03:45
Europe’s imminent privacy overhaul means that we all have to become more diligent about what data we collect, how we collect it, and what we do with it. In our turbulent times, these privacy obligations are about ethics as well as law. Web developers have a major role to play here. After all, healthy data protection practice is as much about the development side — code, data, and security — as it is about the business side of process, information, and strategy.
Categories: Web Design

A Comprehensive Website Planning Guide (Part 2)

Smashing Magazine - Mon, 02/26/2018 - 06:35
In Part 1, I emphasized on the importance of recognizing the purpose of your website, and why planning for the web is just as important as planning for anything else associated with your business. Today, I'd like to go into more detail of evaluating a plan, choosing web professionals, and determining your site structure. Writing The Plan (Or Proposal) Note: The following section is for designers, but everyone ought to understand this part of the process.
Categories: Web Design

A Gentle Introduction to Higher-Order Components in React

Tuts+ Code - Web Development - Mon, 02/26/2018 - 04:00

Higher-Order Components (HOCs) are an interesting technique in React used to refactor similar components that share almost the same logic. I know that it sounds abstract and advanced. However, it is an architectural pattern that isn't specific to React, and hence you can use the approach to do lots of things. 

For instance, you could use it to add a loading indicator to a certain component without tweaking the original component, or you could hide a component's props to make it less verbose. The applications are many, and I've tried to cover most of them in this tutorial.

There are several other tutorials that teach you about HOCs, but most of them are meant for advanced React developers. When I started learning React, I had trouble understanding the concept of higher-order components and how I could incorporate HOCs in my project to write better code. This article will explain everything that you need to know about HOC from scratch to hatch. 


This tutorial is split into three parts. The first part will serve as an introduction to the concept of higher-order components. Here, we shall talk about the syntax you need to know before looking at higher-order functions and HOCs. The second part is the most exciting part of this series where you will see practical examples of HOCs. We will use HOCs for creating forms, authorization, and many other things. 

In the third part of this tutorial, we will focus more on best practices and things to consider while implementing higher-order components. We will also have a brief look at alternative patterns for code sharing in React, such as Render props.

Before getting started, it might be a good idea to take a look at the tutorial on Stateful vs. Stateless components to understand React's component architecture better.

ES6 Syntax Cheatsheet

We will get our hands dirty soon. But before we do, here are some things that I think you should know about. I prefer to use the ES6 syntax wherever possible, and it works great with HOCs. As a beginner, HOC made sense, but some of the ES6 syntax did not. So I recommend going through this section once, and you can come back here later for reference. 

Arrow Functions

Arrow functions are regular function expressions, but with shorter syntax. They are best suited for non-method functions, and that's what we are particularly interested in. Here are some examples to get you started:

Function Without Parameters/* Functions without parameters */ function () { return "This is a function expression"; } // is equivalent to () => { return "This is an arrow function expression" } // or () => "Arrow with a shorter syntax" Function With a Single Parameter/* Function with a single parameter */ function (param) { return { title: "This function accepts a parameter and returns an object", params: param} } // is syntax-equivalent to param => { return { title: "This arrow function accepts a single parameter", params: param } } Function With Multiple Parameters/* Function with multiple parameters */ function (param1, param2) { return { title: "This function accepts multiple parameters", params: [param1,param2]} } // is syntax-equivalent to (param1, param2) => { return {title: "Arrow function with multiple parameters", params: [param1, param2] } } // or (param1, param2) => ({ title: "Arrow function with multiple parameters", params: [param1, param2] }) Currying in Functional Programming

Although the name suggests that it has something to do with an exotic dish from the popular Indian cuisine, it doesn't. Currying helps you break down a function that takes many arguments into a series of functions that take one argument at a time. Here is an example:

//Usual sum function const sum = (a, b) => a + b //Curried sum function const curriedSum = function (a) { return function (b) { return a+b } //Curried sum function using arrow syntax const curriedSum = a => b => a+b curriedSum(5)(4) //9

The function accepts just one argument and returns a function that takes in another argument, and this continues until all the arguments are satisfied. 

curriedSum // (a) => (b) => a+b curriedSum(4) // (b) => 4+b curriedSum(4)(5) //4+5

A closely related term is called partial application. The partial application deals with creating a new function by pre-filling some of the arguments of an existing function. The newly created function will have an arity (which translates to the number of arguments) less than that of the original function.

Spread Syntax

Spread operators spread the contents of an array, string, or object expression. Here is a list of stuff that you can do with spread operators

Spread Syntax in Function Calls/*Spread Syntax in Function Calls */ const add = (x,y,z) => x+y+z const args = [1,2,3] add(...args) // 6 Spread Syntax in Array Literals/* Spread in Array Literals */ const twoAndThree = ['two', 'three']; const numbers = ['one', ...twoAndThree, 'four', 'five']; // ["one", "two", "three", "four", "five"] Spread Syntax in Object Literals/* Spread in Object Literals */ const contactName = { name: { first: "Foo", middle: "Lux", last: "Bar" } } const contactData = { email: "fooluxbar@example.com", phone: "1234567890" } const contact = {...contactName, ...contactData} /* { name: { first: "Foo", middle: "Lux", last: "Bar" } email: "fooluxbar@example.com" phone: "1234567890" } */

I personally love the way in which three dots can make it easier for you to pass down existing props to child components or create new props.

Spread Operator in Reactconst ParentComponent = (props) => { const newProps = { foo: 'default' }; return ( <ChildComponent {...props} {...newProps} /> ) }

Now that we know the basic ES6 syntax for building HOCs, let see what they are.

Higher-Order Functions

What is a higher-order function? Wikipedia has a straightforward definition:

In mathematics and computer science, a higher-order function (also functional, functional form or functor) is a function that either takes one or more functions as arguments or returns a function as its result or both.

You've probably used a higher-order function in JavaScript before in one form or another because that's the way JavaScript works. Passing anonymous functions or callbacks as arguments or a function that returns another function—all this falls under higher-order functions. The code below creates a calculator function which is higher order in nature. 

const calculator = (inputFunction) => (...args) => { const resultValue = inputFunction(...args); console.log(resultValue); return resultValue; } const add = (...all) => { return all.reduce( (a,b) => a+b,0) ; } const multiply = (...all) => { return all.reduce((a,b)=> a*b,1); }

Let's have a deeper look at this. The calculator() accepts a function as input and returns another function—this perfectly fits into our definition of a higher-order function. Because we've used the rest parameter syntax, the function returned collects all its arguments inside an array. 

Then, the input function is invoked with all the arguments passed down, and the output is logged to the console. So the calculator is a curried, higher-order function, and you can use your calculator like this:

calculator(multiply)(2,4); // returns 8 calculator(add)(3,6,9,12,15,18); // returns 63

Plug in a function such as add() or multiply() and any number of parameters, and calculator() will take it from there. So a calculator is a container that extends the functionality of add() and multiply(). It gives us the ability to deal with problems at a higher or more abstract level. At a glance, the benefits of this approach include:

  1. The code can be reused across multiple functions.
  2. You can add extra functionality common to all arithmetic operations at the container level. 
  3. It's more readable, and the intention of the programmer is better expressed.

Now that we have a good idea about higher-order functions, let's see what higher-order components are capable of.

Higher-Order Components

A higher-order component is a function that accepts a component as an argument and returns an extended version of that component. 

(InputComponent) => { return ExtendedComponent } // or alternatively InputComponent => ExtendedComponent

The ExtendedComponent composes the InputComponent. The ExtendedComponent is like a container. It renders the InputComponent, but because we're returning a new component, it adds an extra layer of abstraction. You can use this layer to add state, behavior, or even style. You can even decide not to render the InputComponent at all if you desire—HOCs are capable of doing that and more.

The image below should clear the air of confusion if any.

Enough with the theory—let's get to the code. Here is an example of a very simple HOC that wraps the input component around a <div> tag. From here on, I will be referring to the InputComponent as WrappedComponent because that's the convention. However, you can call it anything you want.

/* The `with` prefix for the function name is a naming convention. You can name your function anything you want as long as it's meaningful */ const withGreyBg = WrappedComponent => class NewComponent extends Component { const bgStyle = { backgroundColor: 'grey', }; render() { return ( <div className="wrapper" style={bgStyle}> <WrappedComponent {...this.props} /> </div> ); } }; const SmallCardWithGreyBg = withGreyBg(SmallCard); const BigCardWithGreyBg = withGreyBg(BigCard); const HugeCardWithGreyBg = withGreyBg(HugeCard); class CardsDemo extends Component { render() { <SmallCardWithGreyBg {...this.props} /> <BigCardWithGreyBg {...this.props} /> <HugeCardWithGreyBg {...this.props /> } }

The withGreyBg function takes a component as an input and returns a new component. Instead of directly composing the Card components and attaching a style tag to each individual components, we create a HOC that serves this purpose. The higher-order component wraps the original component and adds a <div> tag around it. It should be noted that you have to manually pass down the props here at two levels. We haven't done anything fancy, but this is what a normal HOC looks like. The image below demonstrates the withGreyBg() example in more detail.

Although this might not appear particularly useful right now, the benefits are not trivial. Consider this scenario. You are using React router, and you need to keep some routes protected—if the user isn't authenticated, all requests to these routes should be redirected to /login. Instead of duplicating the authentication code, we can use a HOC to effectively manage the protected routes. Curious to know how? We will be covering that and a lot more in the next tutorial.

Note: There a proposed feature in ECMAScript called decorators that makes it easy to use HOCs. However, it is still an experimental feature, so I've decided not to use it in this tutorial. If you're using create-react-app, you will need to eject first to use decorators. If you're running the latest version of Babel (Babel 7), all you need to do is install babel-preset-stage-0 and then add it to the plugin list in your webpack.config.dev.js as follows. 

// Process JS with Babel. { test: /\.(js|jsx|mjs)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, presets: ['stage-0'] },Summary

In this tutorial, we learned the basic concepts of HOCs. HOCs are popular techniques for building reusable components. We started with a discussion of basic ES6 syntax so that it would be easier for you to get used to arrow functions and write modern-day JavaScript code.

We then had a look at higher-order functions and how they work. Finally, we touched on higher-order components and created a HOC from scratch. 

Next up, we will cover different HOC techniques with practical examples. Stay tuned until then. Share your thoughts in the comments section. 

Categories: Web Design

Adobe XD Contest: Create An App Prototype With Your City's Best-Kept Secrets

Smashing Magazine - Mon, 02/26/2018 - 01:40
(This article is kindly sponsored by Adobe.) Every city has its hidden spots: the best place to see the sunset, a cozy coffee shop that makes excellent espresso, or that impressive building you won’t find in any guidebook. As a visitor, you might stumble across little gems like these by chance, but, well, no one knows a city’s secrets as well as the locals, right? Now’s your opportunity to let fellow creatives see your city through your eyes — and to put your design skills to the test at the same time.
Categories: Web Design

Adding Code-Splitting Capabilities To A WordPress Website Through PoP

Smashing Magazine - Fri, 02/23/2018 - 06:30
Speed is among the top priorities for any website nowadays. One way to make a website load faster is by code-splitting: splitting an application into chunks that can be loaded on demand — loading only the required JavaScript that is needed and nothing else. Websites based on JavaScript frameworks can immediately implement code-splitting through Webpack, the popular JavaScript bundler. For WordPress websites, though, it is not so easy. First, Webpack was not intentionally built to work with WordPress, so setting it up will require quite some workaround; secondly, no tools seem to be available that provide native on-demand asset-loading capabilities for WordPress.
Categories: Web Design

Styling Empty Cells With Generated Content And CSS Grid Layout

Smashing Magazine - Thu, 02/22/2018 - 05:00
A common Grid Layout gotcha is when a newcomer to the layout method wonders how to style a grid cell which doesn’t contain any content. In the current Level 1 specification, this isn’t possible since there is no way to target an empty Grid Cell or Grid Area and apply styling. This means that to apply styling, you need to insert an element. In this article, I am going to take a look at how to use CSS Generated Content to achieve styling of empty cells without adding redundant empty elements and show some use cases where this technique makes sense.
Categories: Web Design