20 Best WordPress Calendar Plugins and Widgets

Whether you need an event calendar plugin, a booking system with payments, or a Google calendar widget, this list of plugins will have something to improve your app or site. Take a look at these 20 plugins available for download on Envato Market to see what WordPress is capable of.

WordPress calendar plugins encompass plugins for events, bookings, and appointments. Some transform WordPress into its own private workplace app, while others let you set up a fully functioning scheduling and payment gateway.

Take a look at these 20 WordPress calendar plugins available on Envato Market and you’ll see what I mean.

1. EventOn

The EventOn WordPress event calendar plugin is an excellent turnkey solution that doesn’t skimp on features.

It has a clean, minimal design, and you’ll be up and running quickly and easily.

EventOn - WordPress Event Calendar Plugin

Fully optimized for mobile use, this tiny calendar is big on features:

  • use featured images
  • add your own data fields
  • Google Maps integration
  • calendar widgets and shortcode generator
  • event categories with custom color assignments
  • and much more

Not only can you customize each event with images, maps, icons, colors, and more, but you can also configure your calendar to search and sort in several different ways.

EventOn is a really nice, easy-to-use event calendar plugin that also offers a unique slider addon.

2. SUMO WooCommerce Bookings

SUMO WooCommerce Bookings will transform your WordPress WooCommerce site into a bookings powerhouse.

This is more than just a calendar plugin—it’s a full-fledged WooCommerce booking plugin.

SUMO WooCommerce Bookings

Features include:

  • Google Calendar integration
  • assign users to manage booking availabilities
  • configure reservations and bookings
  • booking detail notifications
  • and much, much more

Appointments, reservations, or events—SUMO WooCommerce Bookings can handle them all.

3. Bookly

You can book and schedule just about anything with this WordPress plugin.

Bookly is an incredible appointment booking system that blurs the line between a WordPress website and a web application.

Bookly - Book Appointments Book Services Book Anything Easy and Fast Booking for Your Clients

This is well designed, fully responsive, and even supports gestures.

You’ll also find:

  • a form builder
  • Google Calendar sync
  • WooCommerce integration
  • SMS and email notifications
  • several online payment gateways
  • and a whole lot more

Customers can book their own appointments, include personal information, and send payment. They can also cancel their own appointments via their confirmation email.

There’s also the ability to create schedules for each staff member—you can even block out holidays.

Bookly‘s customization options and useful features make it more than just a way to serve customers well—it also helps the website owner keep track of staff and appointments at the same time.

4. Calendarize it!

Even though this WordPress calendar plugin is built to work in conjunction with WPBakery Page Builder, it can be used just as easily on its own.

Calendarize it! for WordPress is full of features that can be configured just how you like.

Calendarize it for WordPress

With a very simple design, this calendar plugin can fit in to just about any design scheme or style.

You’ll find many useful features, including, but not limited to:

  • events by user role
  • sidebar widgets and shortcodes
  • Custom Post Types support
  • advanced filtering with custom taxonomies
  • single events, recurring events, arbitrary recurring events, and recurring events with exceptions

You can set up detailed venue pages, leverage Google Maps integration, and use it internationally with multiple languages and date formats.

Calendarize it! is one of the most agile, customizable WordPress calendar plugins.

5. WordPress Pro Event Calendar

There are certain features that you expect with a WordPress calendar plugin; however, there are a few features that really set a plugin apart. Take a look at WordPress Pro Event Calendar and you’ll see a number of advanced features that really make it stand out from the pack.

WordPress Pro Event Calendar

Well designed and fully responsive, this plugin has some really great features:

  • WPML support
  • flexible event settings
  • Google Maps integration
  • subscribe to a calendar
  • custom fields and date range support
  • and more

But what really sets it apart is the ability to import events from ICS feeds and Facebook.

Best of all, WordPress Pro Event Calendar accepts events submitted by front-end users, making it easy for users to add events.

6. Event Booking Pro

Here’s another great option for setting up a fully functional event booking system.

Event Booking Pro is very pro as it boasts over 500 settings!

Event Booking Pro - WP Plugin Paypal or Offline

There are a lot of features with this WordPress calendar plugin, and they are always adding more. Here are a few:

  • unlimited events
  • AJAX control panel
  • offline and multiple booking
  • PayPal, coupon, and CSV integration
  • customize email sent to booker and admin
  • and many, many more

There’s no shortage of shortcodes, it supports CSV, and everything can be customized and styled as you like, making it fit into your WordPress theme design perfectly.

Event Booking Pro is an impressive WordPress calendar plugin.

7. Timetable Responsive Schedule For WordPress

The Timetable Responsive Schedule For WordPress plugin offers a whole different look and approach to WordPress calendar plugins.

With it, you can create a timetable of events easily!

Timetable Responsive Schedule For WordPress

Use the Timetable shortcode generator to create timetable views for classes, medical departments, nightclubs, tutoring, and so on.

Quickly create a timetable by:

  • adding a new event with day, time, category, and more
  • adjust and configure the design and appearance
  • generate your shortcode and place it into a post or page

And that’s it!

There are plenty of event options and many different shortcode options—color picker and font configuration included.

Timetable Responsive Schedule For WordPress also includes a great widget lineup, rounding out one of the best WordPress calendar plugins you’ll find.

8. Booked: Appointment Booking for WordPress

Booked Appointment Booking for WordPress is another solid appointment booking option.

If you’re looking for appointment booking, think about booking Booked.

Booked - Appointment Booking for WordPress

Mobile friendly and with a clean design, this plugin has some nice features:

  • guest booking
  • customer profile pages
  • custom time slots and custom fields
  • customizable customer and admin emails
  • display your calendar with a shortcode or widget
  • and more

I really like the customer profile pages, but being able to display multiple booking agents with assigned calendars is where this WordPress calendar plugin really shines.

If you are considering Booked: Appointment Booking for WordPress, be sure to also look at the Booked add-ons such as Front-End AgentsPayments with WooCommerce, and Calendar Feeds.

9. WordPress Events Calendar Registration & Booking

The WordPress Events Calendar Registration & Booking plugin is feature rich, offering some options you’ll only find in plugin addons.

Everything you need (and maybe more) for successfully setting up a fully functional registration and booking system is right here.

WordPress Events Calendar Registration  Booking

This “out of the box” solution includes:

  • shortcodes
  • color picker
  • multilingual support
  • Google Maps integration
  • recurring events, tickets, and coupons
  • and more

One of the best features, for this plugin and others, is the countdown timer for all your events.

Beautifully designed and leveraging Bootstrap 3.0, the WordPress Events Calendar Registration & Booking should not be overlooked.

10. Booki

Like several of the aforementioned WordPress calendar plugins, Booki offers a full booking system using WordPress.

There are so many great applications for these type of plugins, with each plugin offering a unique perspective on the appointment management process.

Booki - Booking Calendar plugin - A WordPress booking system for online reservation and appointments

You can set up unlimited booking projects and service providers. Options include:

  • add optional extras for bookings
  • online payments via PayPal Express
  • offline payments—book now, pay later
  • admin stats page with summary information
  • sync bookings to a provider’s Google Calendar
  • and more

As for the calendar itself, it displays your booking and appointment calendar with a popup, inline, and more.

Booki is an excellent solution for booking appointments with multiple projects and service providers.

11. Team Booking: WordPress Booking System

This calendar plugin doesn’t try to reinvent the wheel.

Team Booking ties directly into something you’re already probably using: Google Calendar.

Team Booking - WordPress Booking System

Team Booking’s mission is to:

Use Google Calendar to schedule availability.

Additional features include:

  • team booking
  • keep and export your data
  • supports Stripe and PayPal
  • appointment approval system
  • customized forms for each booking type
  • and more

There are also a lot of nice customer features, like displaying reservations and the option to cancel their own appointments.

Team Booking is a fresh take on appointment booking calendars and leverages Google Calendar to the fullest. 

12. WP Booking Calendar

A lot of the WordPress booking calendar plugins include a rich feature set, offering a solid all-in-one solution.

WP Booking Calendar takes a much-needed, refreshingly straightforward approach.

WP Booking Calendar

With minimal configuration, you can set up available time slots, unlimited calendars, confirmations, and more.

Features include:

  • CSV export
  • PayPal integration
  • confirmation emails
  • make multiple reservations
  • unlimited number of time slots and duration
  • and more

You can also set the number of days before a user can make a booking.

WP Booking Calendar is simple without forfeiting great features.

13. Goo Calendar

Goo Calendar is an excellent calendar option.

Build calendars with static and dynamic ranges for your WordPress pages. Once the calendar is set up, publish it, and run it via shortcode on page, post or widget area.

Simple and straightforward, this is a great way to display a full calendar on your website.

Goo Calendar

Features include:

  • both static and dynamic calendars
  • fully customizable to match your look and feel
  • display posts, post meta, Advanced Custom Fields, and custom post types
  • and more

Goo Calendar is a solid solution that provides the basic tools to modify it to your own use.

14. Timetable

A timetable calendar is a great option for situations in which there are several events going on the same day.

Timetable is a plugin with a nice TV guide styled UI and presentation.

Timetable for WordPress

Built on jQuery and CSS3, this plugin lets you add events and modify your timetable from within its modern admin screens.

One of the most powerful features of Timetable is the ability to import and export timetables via CSV. Now you can edit and make changes in Excel or another spreadsheet app and import your changes and added events.

You can also select which program to print, for users who prefer their schedules on paper.

15. Chronosly Event Calendar

Most WordPress calendar plugins focus on the back end and leave most of the design to the designers.

But the Chronosly Event Calendar makes customization as easy as drag and drop.

Chronosly Event Calendar WordPress Plugin

This plugin is fully editable and can be used in one of two ways: basic and advanced.

The advanced features include a whole set of customization tools:

  • custom CSS
  • customize views
  • custom front-end events

Other features include:

  • shortcodes
  • addons marketplace
  • detailed single pages
  • templates marketplace
  • multi-language and Google Maps integration
  • and more

Chronosly Event Calendar can be configured and customized from the comfort of your WordPress admin.

16. Business Calendar

Most of the WordPress calendar plugins we’ve covered focus on the website user.

However, the Business Calendar shifts that focus, as it creates a full-featured internal calendar for each user.

Business Calendar - WordPress Internal Calendar

With the Business Calendar plugin, you can turn a WordPress install into a working platform for business.

Features include:

  • smart invitation system
  • settings are user specific
  • Google Maps localization
  • enable email notifications and reminders
  • creates private page for each event for notes, comments, and file uploads
  • and more

The Business Calendar is a creative approach to using WordPress like an app or full-fledged working platform.

17. HBook: Hotel Booking System

You can use a one-size-fits-all booking plugin for hotels and B&Bs, or you can use a solution built specifically for them.

The HBook hotel booking system is perfect for anyone in the hospitality business.

17 HBook - Hotel Booking System - WordPress Plugin

This snappy plugin includes:

  • seasons
  • rates tables
  • PayPal payment
  • availability calendars
  • booking forms and rules
  • and more

HBook has a clean design and can be configured specifically for hotels, B&Bs, and more!

18. Responsive Event Scheduler

The Responsive Event Scheduler is one of the most beautiful options for publishing event schedules on your website.

It is suitable for music festivals, conferences, conventions, meetings, training, exhibitions etc.

Responsive Event Scheduler

Features include:

  • built with HTML5 and CSS3 — SVG icons enabled
  • one-click color customization
  • event image options
  • fully responsive
  • WPML ready
  • and more

Responsive Event Scheduler is not only impressive from a feature standpoint, but it’s one of the best-looking options you’re going to find.

19. Facebook Events Calendar

Facebook is where everyone is at, but how do you integrate it with your website?

The Facebook Events Calendar is a great way to display your Facebook events online in a super easy way.

Facebook Events Calendar

Features include:

  • displays all events from your Facebook page on the calendar
  • two layouts versions—full and compact
  • using a widget or shortcode, placing this in the page is super easy
  • and more

Facebook Events Calendar is a great way to connect your Facebook with your website.

20. gAppointments: Appointment Booking Addon for Gravity Forms

gAppointments is a great appointment booking addon for Gravity Forms.

If you’re already using Gravity Forms and need to integrate some appointment booking, this solution is certainly worth a look.

gAppointments - Appointment booking addon for Gravity Forms

Features include:

  • supports paid and non-paid booking
  • accepts any payment gateway
  • many options for service intervals and slots
  • and more

Combined with Gravity Forms, gAppointments is a powerful plugin for booking appointments.

Conclusion

WordPress has come a long way since that first default calendar widget. You can see by this list that WordPress has evolved into a web-based tool that can be used day in and day out for all kinds of organizations.

You can dig through Envato Market for more WordPress calendar plugins—and of course, if you can’t find exactly what you’re looking for, you could always code your own!


Source: Nettuts Web Development

20 Best jQuery Image Sliders

Let’s be honest—sliders are fun. A little bit of movement can really bring a page to life.

Sliders—also known as “carousels” or “image sliders”—are interactive elements for showing images or other media in a web page. 

Take a look at these 20 useful jQuery sliders from Envato Market and you’ll see there’s more to sliders than you might have imagined.

1. RoyalSlider

Having a touch-friendly and responsive slider for your website is more important now than ever before, and RoyalSlider is both.

Developed with HTML5 and CSS3 best practices, it’s a solid choice.

RoyalSlider  Touch-Enabled jQuery Image Gallery

Here are a few of the other royally cool features:

  • SEO optimized
  • highly configurable
  • over 10 starter templates
  • includes fallbacks for CSS3 transitions
  • and more

I think the best feature is the modular architecture that gives devs the option to exclude what they don’t need from the main JS file, keeping things as lean as possible.

The RoyalSlider is a solid JavaScript slider that should be a nice addition to any web dev’s toolbox.

2. Slider Revolution

It’s not easy to be “revolutionary” in the slider space. There are only so many options you can make available when it comes to sliders, but the Slider Revolution does a great job trying.

When it comes to jQuery sliders, this one delivers on just about everything you’ll want.

Slider Revolution Responsive jQuery Plugin

The list of features for this slider is long, so I’ll just hit the high points:

  • parallax effects and custom animations
  • SEO optimized and lazy loading options
  • add unlimited layers and slides with link options
  • includes “ready to use” styles and is highly customizable
  • and much more

The ability to drop in an image, video player embed, and social media source makes Slider Revolution one of the most flexible and customizable options you’ll find.

3. LayerSlider

The name doesn’t do this jQuery slider justice. Its 200+ 2D and 3D slide transitions will turn some heads.

LayerSlider Responsive jQuery Slider Plugin

Some of the notable features include:

  • skin design PSD template included
  • 13 skins and 3 navigation types
  • add a fixed image over the slider
  • SEO friendly and lazy load images
  • hardware-accelerated CSS3 transitions with jQuery fallback
  • and more

Like the previous slider, you can drop in just about any content—even HTML5 self-hosted multimedia content.

The LayerSlider brings a lot of action to the slider space and is downright handsome.

4. jQuery Banner Rotator / Slideshow

The jQuery Banner Rotator / Slideshow slider is a straightforward solution. It’s simple without sacrificing essentials.

jQuery Banner Rotator  Slideshow

It includes:

  • tooltips, text descriptions, etc.
  • thumbnail and component viewing options
  • timer and delay options on a global or per-slider basis
  • multiple transitions for all slides or different for each one
  • more

While the jQuery Banner Rotator / Slideshow is basic compared to other jQuery sliders, it should not be overlooked if you want a simple, clean interface.

5. All In One Slider Responsive jQuery Slider Plugin

Every slider comes to market with its own unique perspective and provides a solution to whatever slider niche is being targeted.

But not this one.

The All In One Slider Responsive jQuery Slider Plugin is… well… all in one.

All In One Slider Responsive Jquery Slider Plugin

I think most web devs and designers have a go-to solution, but at the same time are always on the lookout for something new.

This just might be that something new as it includes:

  • banner rotator
  • thumbnails banner
  • banner with playlist
  • content slider
  • carousel

And all of these slider styles include most—if not all—of the features needed in a jQuery slider.

Will the All In One Slider Responsive jQuery Slider Plugin be your all-in-one slider solution?

6. UnoSlider

If your slider isn’t touch-enabled and responsive, you’re not doing it right.

The UnoSlider does it right.

UnoSlider - Responsive Touch Enabled Slider

This slider finds its sweet spot between simple and feature rich.

Features include:

  • easily themeable
  • 12 pre-built themes
  • 40 present transitions
  • IE6+ support (because it’s still out there!)
  • and more

The feature set leans more towards design and style, making the UnoSlider a great content slider to theme.

7. Master Slider

Looking for one jQuery slider to rule them all?

Try the Master Slider on for size…

Master Slider - jQuery Touch Swipe Slider

When it comes to good looks, this one is in the upper echelon:

  • smart preloading
  • over 25 templates
  • hardware-accelerated transitions
  • supports touch navigation and swipe gestures
  • and much more

The interactive transitions, animated layers, and hotspots will really catch your eye.

The Master Slider collection is a masterpiece.

8. TouchCarousel

TouchCarousel touts “free support and upgrades”, but there’s a lot more to this lightweight carousel-style jQuery slider.

TouchCarousel - jQuery Content Scroller and Slider

With “touch” in the name, it’s obviously fully responsive and supports touch navigation.

Other features include:

  • SEO friendly
  • smart autoplay
  • hardware-accelerated CSS3 transitions
  • customizable UI with four Photoshop skins
  • and more

However, TouchCarousel takes mobile to a whole new level with its unique physics-based scrolling.

9. Advanced Slider

A jQuery slider isn’t just for the web. It can also be useful when integrated into applications, just like you can do with the Advanced Slider.

Advanced Slider - jQuery XML Slider

Using HTML markup or XML, this advanced slider packs a lot of punch:

  • animated layers and smart video
  • 100+ transitions and 150+ customizable properties
  • 15 slider skins, 7 scrollbar skins, and built-in lightbox support
  • keyboard navigation, touchscreen support, and fully customizable interface
  • and much, much more

The best feature, however, has got to be the Advanced Slider API—making it the perfect slider solution for your application.

10. jQuery Slider Zoom In/Out Effect Fully Responsive

This is one of those jQuery sliders that makes you visit the demo before you start reading about the features, because you want to know what the heck “zoom in/out effect” even means.

Think screensaver.

jquery Slider Zoom InOut Effect Fully Responsive

While the effect is fairly slight, the zoom effect in a slider adds a nice touch in a world wide web full of static image sliders.

This slick slider’s features include:

  • CSS3 layer transitions
  • exit animation parameters for layers
  • fixed, full width, and fullscreen options
  • CSS and HTML formatted animated text
  • and more

While most sliders try to deliver many effects in one package, the jQuery Slider Zoom In/Out Effect Fully Responsive slider delivers the Ken Burns effect and delivers it well.

11. Content Timeline

Content Timeline is a beautifully designed and powerful slider—a perfect solution for timelines.

From desktop to mobile, timelines have never looked so good.

Content Timeline

It’s simple. Take your content, sort it by the date, call the function, and that’s it!

Features include:

  • powerful and lightweight
  • 11 customizable settings
  • fully interactive, flexible, and intuitive
  • full responsive and built for mobile and desktop
  • and more

With seven embedded script control methods and included easing effects, Content Timeline is one of the best timeline sliders you’ll find.

12. Sexy Slider

The Sexy Slider isn’t nearly as sexy as it used to be, but it has aged well, making it a trustworthy solution.

Sexy Slider

It’s not very impressive at first blush, but with some fine-tuning, this flexible jQuery slider can be configured to fit your design perfectly.

It includes:

  • auto slide
  • image captions
  • continuous sliding
  • 6 transition effects
  • and more

Sexy Slider is just waiting for you to unlock its power and discover its full potential.

13. Master Slider jQuery Slider Plugin with Visual Builder

The Master Slider jQuery Slider Plugin with Visual Builder makes building a slider a snap—without sacrificing good looks.

This premium image and content slider offers some really nice hardware-accelerated transitions that will surely catch your eye.

Master Slider jQuery Slider Plugin with Visual Builder

Features include:

  • smart preloading
  • built for both mobile and desktop
  • over 80 ready-to-use sample sliders
  • masked layer transitions, layer actions, and overlay layers
  • and more

Master Slider jQuery Slider Plugin with Visual Builder is fully customizable, SEO friendly, and also supports videos. And of course, the most obvious: a visual builder.

14. Translucent

Most jQuery slider plugins include some sort of design chrome, and while you can configure it to your liking, sometimes you just want to keep everything contained within the slide itself.

Enter the Translucent slider.

Translucent - Responsive Banner Rotator  Slider

There are a lot of presets, so all you’ll need to do is configure it and go!

Features include:

  • 6 style variations
  • 4 transition effects
  • 2 touch swipe transitions
  • configurable buttons and captions
  • and more

Like others, it’s touch-friendly, responsive, and leverages hardware acceleration.

Translucent is a minimal slider design that does a great job pushing the content to the front.

15. Unleash

Looking for an accordion slider? Then Unleash is what you want!

Packed with features, this beautiful slider is one of the best accordion sliders you’ll find.

Unleash

Features include:

  • HTML5 video support for desktop
  • hardware-accelerated animations
  • fully responsive
  • supports touch
  • and more

Unleash the Unleash jQuery responsive accordion slider.

16. AviaSlider

AviaSlider is another good-looking slider that includes some really nice effects.

This easy-to-use jQuery slideshow plugin includes eight predefined transitions, but you can create more.

AviaSlider

Some other features include:

  • includes image preloader
  • autoplay stops when users interact
  • works with prettyPhoto Lightbox out of the box
  • and more

AviaSlider packs a punch, despite the packed version weighing in at only 8kb.

17. Slider Evolution

Start a slider revolution with Slider Evolution! Now you can easily create JavaScript sliders with some of the best effects.

Slider Evolution

With Slider Evolution, you can create an unlimited number of sliders, each with customized settings, to be placed anywhere on your website.

18. Accordionza

jQuery sliders don’t get much lighter than this.

Using only 3kb to load, Accordionza is a super lightweight accordion slider option.

Accordionza - jQuery Plugin

And if you don’t like the three included styles, you can tweak the HTML and CSS of this flexible accordion.

Features include:

  • keyboard navigation
  • easily configure effects and controls
  • progressive enhancement (viewable without JavaScript enabled)
  • and more

Keep in mind that Accordionza can display many kinds of mixed content, making it an excellent choice for a flexible, go-to accordion slider option.

19. mightySlider

The mightySlider is mighty indeed.

You can use it not only as a simple image slider, but also as a full one-directional slider with item-based navigation—making for a nice one-page website design.

mightySlider - Responsive Multipurpose Slider

You’ll find plenty of options under the hood:

  • keyboard, mouse, and touch support
  • hardware-accelerated CSS3 transitions
  • clean, valid markup and SEO optimized
  • unlimited slides, caption layers, and caption effects
  • and much more

The API is powerful and developer-friendly, adding to the many ways it can be used.

With its clean and well-commented code, the mightySlider is an excellent, forward-thinking jQuery slider.

20. Parallax Slider

The Parallax Slider works like the jQuery Responsive OneByOne Slider Plugin, allowing you to animate each layer separately within a particular slide.

You can do this with multiple slides, or even just one slide, adding some compelling parallax animation to your website.

Parallax Slider - Responsive jQuery Plugin

This comes with four different types of sliders, all offering the same animated, parallax effect.

Like many other jQuery sliders, it also includes:

  • fully customizable
  • touchscreen support
  • fully responsive and unlimited layers
  • autoplay, loop, height & width, and timer parameters
  • and more

Animated layers are not limited to text and images either. You can also include YouTube, Vimeo, and HTML5 video.

The Parallax Slider is another fine example of how Flash-like effects can be executed better than Flash—and be supported across all devices.

Conclusion

It’s interesting to see how the jQuery slider has evolved from something that just transitioned from one image to the next, into a broad range of creative tools. We see sliders that are 3D, parallax, full page, and are fully responsive and viewable on the desktop or smartphone.

If you didn’t find a jQuery slider you liked in this list, you could always take an Envato Tuts+ jQuery Code Tutorial and develop something completely new and unique. Otherwise, dig through the many other great jQuery sliders on Envato Market—there are plenty to choose from.

What’s your favorite jQuery slider and why?


Source: Nettuts Web Development

How Secure Are Your JavaScript Open-Source Dependencies?

Modern-day JavaScript developers love npm. GitHub and the npm registry are a developer’s first choice place for finding a particular package. Open-source modules add to the productivity and efficiency by providing developers with a host of functionalities that you can reuse in your project. It is fair to say that if it were not for these open-source packages, most of the frameworks today would not exist in their current form.

A full-fledged enterprise-level application, for instance, might rely on hundreds if not thousands of packages. The usual dependencies include direct dependencies, development dependencies, bundled dependencies, production dependencies, and optional dependencies. That’s great because everyone’s getting the best out of the open-source ecosystem.

However, one of the factors that get overlooked is the amount of risk involved. Although these third-party modules are particularly useful in their domain, they also introduce some security risks into your application.

Are Open-Source Libraries Vulnerable?

OSS dependencies are indeed vulnerable to exploits and compromises. Let’s have a look at a few examples: 

A vulnerability was discovered recently in a package called eslint-scope which is a dependency of several popular JavaScript packages such as babel-eslint and webpack. The account of the package maintainer was compromised, and the hackers added some malicious code into it. Fortunately, someone found out the exploit soon enough that the damage was reportedly limited to a few users. 

Moment.js, which is one of the most-used libraries for parsing and displaying dates in JavaScript, was recently found to have a vulnerability with a severity score of 7.5. The exploit made it vulnerable to ReDoS attacks. Patches were quickly released, and they were able to fix the issue rather quickly.

But that’s not all. A lot of new exploits get unearthed every week. Some of them get disclosed to the public, but others make headlines only after a serious breach. 

So how do we mitigate these risks? In this article, I’ll explain some of the industry-standard best practices that you can use to secure your open-source dependencies.

1. Keep Track of Your Application’s Dependencies

Logically speaking, as the number of dependencies increase, the risk of ending up with a vulnerable package can also increase. This holds true equally for direct and indirect dependencies. Although there’s no reason that you should stop using open-source packages, it’s always a good idea to keep track of them.

These dependencies are easily discoverable and can be as simple as running npm ls in the root directory of your application. You can use the –prod argument which displays all production dependencies and the –long argument for a summary of each package description. 

Furthermore, you can use a service to automate the dependency management process that offers real-time monitoring and automatic update testing for your dependencies. Some of the familiar tools include GreenKeeper, Libraries.io, etc. These tools collate a list of the dependencies that you are currently using and track relevant information regarding them.

2. Get Rid of Packages That You Do Not Need

With the passage of time and changes in your code, it is likely that you’ll stop using some packages altogether and instead add in new ones. However, developers tend not to remove old packages as they go along.

Over time, your project might accumulate a lot of unused dependencies. Although this is not a direct security risk, these dependencies almost certainly add to your project’s attack surface and lead to unnecessary clutter in the code. An attacker may be able to find a loophole by loading an old but installed package that has a higher vulnerability quotient, thereby increasing the potential damage it can cause.

How do you check for such unused dependencies? You can do this with the help of the depcheck tool. Depcheck scans your entire code for requires and import commands. It then correlates these commands with either installed packages or those mentioned in your package.json and provides you with a report. The command can also be modified using different command flags, thereby making it simpler to automate the checking of unused dependencies.

Install depcheck with:

3. Find and Fix Crucial Security Vulnerabilities

Almost all of the points discussed above are primarily concerned with the potential problems that you might encounter. But what about the dependencies that you’re using right now?

Based on a recent study, almost 15% of current packages include a known vulnerability, either in the components or dependencies. However, the good news is that there are many tools that you can use to analyze your code and find open-source security risks within your project.

The most convenient tool is npm’s npm audit. Audit is a script that was released with npm’s version 6. Node Security Platform initially developed npm audit, and npm registry later acquired it. If you’re curious to know what npm audit is all about, here’s a quote from the official blog:

A security audit is an assessment of package dependencies for security vulnerabilities. Security audits help you protect your package’s users by enabling you to find and fix known vulnerabilities in dependencies. The npm audit command submits a description of the dependencies configured in your package to your default registry and asks for a report of known vulnerabilities. 

The report generated usually comprises of the following details: the affected package name, vulnerability severity and description, path, and other information, and, if available, commands to apply patches to resolve vulnerabilities. You can even get the audit report in JSON by running npm audit --json.

Apart from that, npm also offers assistance on how to act based on the report. You can use npm audit fix to fix issues that have already been found. These fixes are commonly accomplished using guided upgrades or via open-source patches. 

Feel free to refer npm’s documentation for more information.

4. Replace Expired Libraries With In-House Alternatives 

The concept of open-source security is heavily reliant on the number of eyes that are watching over that particular library. Packages that are actively used are more closely watched. Therefore, there is a higher chance that the developer might have addressed all the known security issues in that particular package. 

Let’s take an example. On GitHub, there are many JSON web token implementations that you can use with your Node.js library. However, the ones that are not in active development could have critical vulnerabilities. One such vulnerability, which was reported by Auth0, lets anyone create their own “signed” tokens with whatever payload they want. 

If a reasonably popular or well-used package had this flaw, the odds of a developer finding and patching the fault would be higher. But what about an inactive/abandoned project? We’ll talk about that in the next point.

5. Always Choose a Library That’s in Active Development

Perhaps the quickest and most efficient way to determine the activity of a specific package is to check its download rate on npm. You can find this in the Stats section of npm’s package page. It is also possible to extract these figures automatically using the npm stats API or by browsing historic stats on npm-stat.com. For packages with GitHub repositories, you should check out the commit history, the issue tracker, and any relevant pull requests for the library.

6. Update the Dependencies Frequently

There are many bugs, including a large number of security bugs that are continually unearthed and, in most cases, immediately patched. It is not uncommon to see recently reported vulnerabilities being fixed solely on the most recent branch/version of a given project.

For example, let’s take the Regular Expression Denial of Service (ReDoS) vulnerability reported on the HMAC package ‘hawk’ in early 2016. This bug in hawk was quickly resolved, but only in the latest major version, 4.x. Older versions like 3.x were patched a lot later even though they were equally at risk. 

Therefore, as a general rule, your dependencies are less likely to have any security bugs if they use the latest available version. 

The easiest way to confirm if you’re using the latest version is by using the npm outdated command. This command supports the -prod flag to ignore any dev dependencies and --json to make automation simpler.

Regularly inspect the packages you use to verify their modification date. You can do this in two ways: via the npm UI, or by running npm view <package> time.modified.

Conclusion

The key to securing your application is to have a security-first culture from the start. In this post, we’ve covered some of the standard practices for improving the security of your JavaScript components. 

  1. Use open-source dependencies that are in active development.
  2. Update and monitor your components.
  3. Review your code and write tests.
  4. Remove unwanted dependencies or use alternatives.
  5. Use security tools like npm audit to analyze your dependencies.

If you have any thoughts about JavaScript security, feel free to share them in the comments.


Source: Nettuts Web Development

New Course: Secure Your WordPress Site With SSL

These days, it’s more important than ever for your WordPress site to use a SSL (Secure Sockets Layer) certificate, which encrypts the data between the client and the server. Browsers now mark sites as “secure” or “not secure”, and using SSL can boost your search engine rankings. Plus, of course, there are the obvious security benefits.

In our new Coffee Break Course, Secure Your WordPress Site With SSL, Envato Tuts+ instructor Bilal Shahid will show you how to get and install free SSL certificates using Certbot and Let’s Encrypt—a free and open certificate authority aiming to support a more secure and privacy-respecting web.

Lets Encrypt

Watch the introduction below to find out more.

 

You can take our new Coffee Break 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 650,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.


Source: Nettuts Web Development

Testing Components in React Using Jest and Enzyme

This is the second part of the series on Testing Components in React. If you have prior experience with Jest, you can skip ahead and use the GitHub code as a starting point. 

In the previous article, we covered the basic principles and ideas behind test-driven development. We also set up the environment and the tools required for running tests in React. The toolset included Jest, ReactTestUtils, Enzyme, and react-test-renderer. 

We then wrote a couple of tests for a demo application using ReactTestUtils and discovered its shortcomings compared to a more robust library like Enzyme.

In this post, we’ll get a deeper understanding of testing components in React by writing more practical and realistic tests. You can head to GitHub and clone my repo before getting started.

Getting Started With the Enzyme API

Enzyme.js is an open-source library maintained by Airbnb, and it’s a great resource for React developers. It uses the ReactTestUtils API underneath, but unlike ReactTestUtils, Enzyme offers a high-level API and easy-to-understand syntax. Install Enzyme if you haven’t already.

The Enzyme API exports three types of rendering options:

  1. shallow rendering
  2. full DOM rendering
  3. static rendering

Shallow rendering is used to render a particular component in isolation. The child components won’t be rendered, and hence you won’t be able to assert their behavior. If you’re going to focus on unit tests, you’ll love this. You can shallow render a component like this:

Full DOM rendering generates a virtual DOM of the component with the help of a library called jsdom. You can avail this feature by replacing the shallow() method with mount() in the above example. The obvious benefit is that you can render the child components also. If you want to test the behavior of a component with its children, you should be using this. 

Static rendering is used to render react components to static HTML. It’s implemented using a library called Cheerio, and you can read more about it in the docs

Revisiting Our Previous Tests

Here are the tests that we wrote in the last tutorial:

src/components/__tests__/ProductHeader.test.js

The first test checks whether the ProducerHeader component has an <h2> tag, and the second one finds whether it has a CSS class named title. The code is hard to read and understand. 

Here are the tests rewritten using Enzyme.

src/components/__tests__/ProductHeader.test.js

First, I created a shallow-rendered DOM of the <ProductHeader/> component using shallow() and stored it in a variable. Then, I used the .find() method to find a node with tag ‘h2’. It queries the DOM to see if there’s a match. Since there is only one instance of the node, we can safely assume that node.length will be equal to 1.

The second test is very similar to the first one. The hasClass('title') method returns whether the current node has a className prop with value ‘title’. We can verify the truthfulness using toBeTruthy().  

Run the tests using yarn test, and both the tests should pass. 

Well done! Now it’s time to refactor the code. This is important from a tester’s perspective because readable tests are easier to maintain. In the above tests, the first two lines are identical for both the tests. You can refactor them by using a beforeEach() function.  As the name suggests, the beforeEach function gets called once before each spec in a describe block is executed. 

You can pass an arrow function to beforeEach() like this.

src/components/__tests__/ProductHeader.test.js

Writing Unit Tests With Jest and Enzyme

Let’s write a few unit tests for the ProductDetails component. It is a presentational component that displays the details of each individual product. 

Testing Components in React - ProductDetails component highlighted
We’re going to test the section that’s highlighted

The unit test will try to assert the following assumptions:

  • The component exists and the props are getting passed down.
  • The props like product’s name, description, and availability are displayed.
  • An error message is displayed when the props are empty.

Here is the bare-bones structure of the test. The first beforeEach() stores the product data in a variable, and the second one mounts the component.

src/components/__tests__/ProductDetails.test.js

The first test is easy:

Here we use the props() method which is handy for getting the props of a component.

For the second test, you can query elements by their class names and then check whether the product’s name, description etc. are part of that element’s innerText

The text() method is particularly useful in this case to retrieve the inner text of an element. Try writing an expectation for the product.status() and see if all the tests are passing.

For the final test, we’re going to mount the ProductDetails component without any props. Then we’re going to look for a class named ‘.product-error’ and check if it contains the text “Sorry, Product doesn’t exist”.

That’s it. We’ve successfully tested the <ProductDetails /> component in isolation. Tests of this type are known as unit tests.

Testing Callbacks Using Stubs and Spies

We just learned how to test props. But to truly test a component in isolation, you also need to test the callback functions. In this section, we’ll write tests for the ProductList component and create stubs for callback functions along the way. Here are the assumptions that we need to assert.

Testing components in React - ProductList Component
  1. The number of products listed should be equivalent to the number of objects the component receives as props.
  2. Clicking on <a> should invoke the callback function.

Let’s create a beforeEach() function that fills in mock product data for our tests.

src/components/__tests__/ProductList.test.js

Now, let’s mount our component in another beforeEach() block.

The ProductList receives the product data through props. In addition to that, it receives a callback from the parent. Although you could write tests for the parent’s callback function, that’s not a great idea if your aim is to stick to unit tests. Since the callback function belongs to the parent component, incorporating the parent’s logic will make the tests complicated. Instead, we are going to create a stub function.

What’s a Stub? 

A stub is a dummy function that pretends to be some other function. This allows you to independently test a component without importing either parent or child components. In the example above, we created a stub function called handleProductClick by invoking jest.fn()

Now we just need to find the all the <a> elements in the DOM and simulate a click on the first <a> node. After being clicked, we’ll check if handleProductClick() was invoked. If yes, it’s fair to say our logic is working as expected.

Enzyme lets you easily simulate user actions such as clicks using simulate() method. handlerProductClick.mock.calls.length returns the number of times the mock function was called. We expect it to be equal to 1.

The other test is relatively easy. You can use the find() method to retrieve all <a> nodes in the DOM. The number of <a> nodes should be equal to the length of the productData array that we created earlier. 

Testing the Component’s State, LifeCycleHook, and Method

Next up, we’re going to test the ProductContainer component. It has a state, a lifecycle hook, and a class method. Here are the assertions that need to be verified:

  1. componentDidMount is called exactly once.
  2. The component’s state is populated after the component mounts.
  3. The handleProductClick() method should update the state when a product id is passed in as an argument.

To check whether componentDidMount was called, we’re going to spy on it. Unlike a stub, a spy is used when you need to test an existing function. Once the spy is set, you can write assertions to confirm whether the function was called.

You can spy on a function as follows:

src/components/__tests__/ProductContainer.test.js

The first parameter to jest.spyOn is an object that defines the prototype of the class that we’re spying on. The second one is the name of the method that we want to spy. 

Now render the component and create an assertion to check whether spy was called.

To check that the component’s state is populated after the component mounts, we can use Enzyme’s state() method to retrieve everything in the state. 

The third one is a bit tricky. We need to verify that handleProductClick is working as expected. If you head over to the code, you’ll see that the handleProductClick() method takes a product id as input, and then updates this.state.selectedProduct with the details of that product. 

To test this, we need to invoke the component’s method, and you can actually do that by calling component.instance().handleProductClick(). We’ll pass in a sample product id. In the example below, we use the id of the first product. Then, we can test whether the state was updated to confirm that the assertion is true. Here’s the whole code:

We’ve written 10 tests, and if everything goes well, this is what you should see:

Final output with tests passing

Summary

Phew! We’ve covered almost everything that you need to know to get started with writing tests in React using Jest and Enzyme. Now might be a good time to head over to the Enzyme website to have a deeper look at their API.

What are your thoughts on writing tests in React? I’d love to hear them in the comments.


Source: Nettuts Web Development

Testing Components in React Using Jest: The Basics

Final product image
What You’ll Be Creating

Testing code is a confusing practice for many developers. That’s understandable because writing tests requires more effort, time, and the ability to foresee possible use cases. Startups and developers working on smaller projects usually favor ignoring tests altogether because of the lack of resources and manpower. 

However, there are a couple of reasons why I believe that you should test your components:

  1. It makes you feel more confident about your code.
  2. Tests enhance your productivity.

React isn’t any different either. When your whole application starts to turn into a pile of components that are hard to maintain, testing offers stability and consistency. Writing tests from day one will help you write better code, spot bugs with ease, and maintain a better development workflow. 

In this article, I will take you through everything that you need to know to write tests for your React components. I’ll also cover some of the best practices and techniques while we’re at it. Let’s get started!

Testing Components in React

Testing is the process of verifying that our test assertions are true and that they stay true throughout the lifetime of the application. A test assertion is a boolean expression that returns true unless there is a bug in your code. 

For instance, an assertion could be something as simple as this: “When the user navigates to /login, a modal with the id #login should be rendered.” So, if it turns out that you messed up the login component somehow, the assertion would return false. Assertions are not just limited to what gets rendered—you can also make assertions about how the application responds to user interactions and other actions. 

There are many automated testing strategies that front-end developers use to test their code. We will limit our discussion to just three software test paradigms that are popular with React: unit testing, functional testing, and integration testing.

Unit Testing

Unit testing is one of the test veterans that’s still popular in testing circles. As the name suggests, you will be testing individual pieces of code to verify that they function independently as expected. Because of React’s component architecture, unit tests are a natural fit. They’re also faster because you don’t have to rely on a browser.

Unit tests help you think of each component in isolation and treat them as functions. Your unit tests for a particular component should answer the following questions:

  1. Are there any props? If yes, what does it do with them?
  2. What components does it render? 
  3. Should it have a state? When or how should it update the state?
  4. Is there a procedure that it should follow when it mounts or unmounts, or on user interaction?

Functional Testing

Functional tests are used to test the behavior of a part of your application. Functional tests are usually written from a user’s perspective. A piece of functionality is usually not limited to a single component. It can be a full-fledged form or an entire page. 

For instance, when you’re building a signup form, it might involve components for the form elements, the alerts, and errors if any. The component that gets rendered after the form is submitted is also part of that functionality. This doesn’t require a browser renderer because we’ll be using an in-memory virtual DOM for our tests.

Integration Testing

Integration testing is a test strategy where all the individual components are tested as a group. Integrated testing attempts to replicate the user experience by running the tests on an actual browser. This is considerably slower than functional testing and unit tests because each test suite is executed on a live browser. 

In React, unit tests and functional tests are more popular than integration tests because they are easier to write and maintain. That’s what we will cover in this tutorial.

Know Your Tools 

You need certain tools and dependencies to get started with unit and functional testing your React application. I’ve listed them below.

Jest Test Framework

Jest is a testing framework that requires zero configuration and is therefore easy to set up. It’s more popular than test frameworks like Jasmine and Mocha because it’s developed by Facebook. Jest is also faster than the rest because it uses a clever technique to parallelize test runs across workers. Apart from that, each test runs in a sandbox environment so as to avoid conflicts between two successive tests. 

If you’re using create-react-app, it comes shipped with Jest. If not, you might have to install Jest and a few other dependencies. You can read more about it on the official Jest documentation page

react-test-renderer

Even if you’re using create-react-app, you will need to install this package to render snapshots. Snapshot testing is a part of the Jest library. So, instead of rendering the UI of the entire application, you can use the test renderer to quickly generate a serializable HTML output from the virtual DOM. You can install it as follows:

ReactTestUtils and Enzyme

react-dom/test-utils consists of some of the test utilities provided by the React team. Alternatively, you can use the Enzyme package released by Airbnb. Enzyme is a whole lot better than ReactTestUtils because it is easy to assert, manipulate, and traverse your React Components’ output. We will start our tests with React utils and then transition to Enzyme later on.

To install Enzyme, run the following command.

Add the code to src/SetupTests.js.

There is more information about this in the Testing Components section of the create-react-app page. 

Setting Up a Demo App and Organizing Tests

We will be writing tests for a simple demo application that displays a master/detail view of a list of products. You can find the demo application in our GitHub repo. The application consists of a container component known as ProductContainer and three presentational components: ProductList, ProductDetails, and ProductHeader

Directory Structure

This demo is a good candidate for unit testing and functional testing. You can test each component in isolation and/or test the product listing functionality as a whole. 

Once you’ve downloaded the demo, create a directory with the name __tests__ inside /src/components/. You can then store all the test files related to this functionality inside the __tests__ directory. Testers usually name their test files as either .spec.js or .test.js—for example, ProductHeader.test.js or ProductHeader.spec.js

Writing Basic Tests in React

Create a ProductHeader.test.js file if you haven’t already. Here is what our tests are basically going to look like:

src/components/__tests__/ProductList.test.js

The test suite starts with a describe block, which is a global Jest function that accepts two parameters. The first parameter is the title of the test suite, and the second parameter is the actual implementation. Each it() in a test suite corresponds to a test or a spec. A test contains one or more expectations that check the state of the code. 

In Jest, an expectation is an assertion that either returns true or false. When all the assertions in a spec are true, it is said to pass. Otherwise, the test is said to fail.

For instance, we’ve created two test specs. The first one should obviously pass, and the second one should fail. 

Note: toBeTruthy() is a predefined matcher. In Jest, each matcher makes a comparison between the expected value and the actual value and returns a boolean. There are many more matchers available, and we will have a look at them in a moment.

Running the Test Suite

create-react-app has set up everything that you need to execute the test suite. All you need to do is run the following command:

You should see something like this:

Test output

To make the failing test pass, you have to replace the toBeTruthy() matcher with toBeFalsy().

That’s it!

Using Matchers in Jest

As mentioned earlier, Jest uses matchers to compare values. You can use it to check equality, compare two numbers or strings, and verify the truthiness of expressions. Here is the list of popular matchers available in Jest. 

  • toBe();
  • toBeNull()
  • toBeDefined()
  • toBeUndefined()
  • toBeTruthy()
  • toBeFalsy()
  • toBeGreaterThan()
  • toBeLesserThan()
  • toMatch()
  • toContain()

This is just a taste. You can find all the available matchers in the reference docs.

Testing a React Component

First, we’ll be writing a couple of tests for the ProductHeader component. Open up the ProductHeader.js file if you haven’t already. 

src/components/ProductHeader.js

Are you curious to know why I used a class component here instead of a functional component? The reason is that it’s harder to test functional components with ReactTestUtils. If you’re curious to know why, this Stack Overflow discussion has the answer.

We could write a test with the following assumptions:

  1. The component should render an h2 tag.
  2. The h2 tag should have a class named title.

To render a component and to retrieve relevant DOM nodes, we need ReactTestUtils. Remove the dummy specs and add the following code:

src/components/__tests__/ProductHeader.test.js

To check for the existence of an h2 node, we will first need to render our React elements into a DOM node in the document. You can do that with the help of some of the APIs exported by ReactTestUtils. For instance, to render our <ProductHeader/> component, you can do something like this:

Then, you can extract the h2 tag from the component with the help of findRenderedDOMComponentWithTag('tag-name'). It checks all the child nodes and finds the node that matches the tag-name

Here is the whole test spec.

Try saving it, and your test runner should show you that the test has passed. That’s somewhat surprising because we don’t have an expect() statement like in our previous example. Most of the methods exported by ReactTestUtils have expectations built into them. In this particular case, if the test utility fails to find the h2 tag, it will throw an error and the tests will automatically fail.

Now, try creating the code for the second test. You can use findRenderedDOMcomponentWithClass() to check if there’s any node with the class ‘title’.

That’s it! If all goes well, you should see the results in green. 

Test results

Conclusion

Although we just wrote two test specs, we’ve covered a lot of ground in the process. In the next article, we’ll write some full-fledged tests for our product listing page. We’ll also replace ReactTestUtils with Enzyme. Why? Enzyme offers a high-level interface that’s very easy to use and developer-friendly. Stay tuned for the second part!

If at any point you feel stuck or need help, let us know in the comments. 


Source: Nettuts Web Development

Set Up Routing in PHP Applications Using the Symfony Routing Component

Today, we’ll go through the Symfony Routing component, which allows you to set up routing in your PHP applications.

What Is the Symfony Routing Component?

The Symfony Routing Component is a very popular routing component which is adapted by several frameworks and provides a lot of flexibility should you wish to set up routes in your PHP application.

If you’ve built a custom PHP application and are looking for a feature-rich routing library, the Symfony Routing Component is more than a worth a look. It also allows you to define routes for your application in the YAML format.

Starting with installation and configuration, we’ll go through real-world examples to demonstrate a variety of options the component has for route configuration. In this article, you’ll learn:

  • installation and configuration
  • how to set up basic routes
  • how to load routes from the YAML file
  • how to use the all-in-one router

Installation and Configuration

In this section, we’re going to install the libraries that are required in order to set up routing in your PHP applications. I assume that you’ve installed Composer in your system as we’ll need it to install the necessary libraries that are available on Packagist.

Once you’ve installed Composer, go ahead and install the core Routing component using the following command.

Although the Routing component itself is sufficient to provide comprehensive routing features in your application, we’ll go ahead and install a few other components as well to make our life easier and enrich the existing core routing functionality.

To start with, we’ll go ahead and install the HttpFoundation component, which provides an object-oriented wrapper for PHP global variables and response-related functions. It makes sure that you don’t need to access global variables like $_GET, $_POST and the like directly.

Next, if you want to define your application routes in the YAML file instead of the PHP code, it’s the YAML component that comes to the rescue as it helps you to convert YAML strings to PHP arrays and vice versa.

Finally, we’ll install the Config component, which provides several utility classes to initialize and deal with configuration values defined in the different types of file like YAML, INI, XML, etc. In our case, we’ll use it to load routes from the YAML file.

So that’s the installation part, but how are you supposed to use it? In fact, it’s just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.

Set Up Basic Routes

In the previous section, we went through the installation of the necessary routing components. Now, you’re ready to set up routing in your PHP application right away.

Let’s go ahead and create the basic_routes.php file with the following contents.

Setting up routing using the Symfony Routing component usually goes through a series of steps as listed below.

  • Initialize the Route object for each of your application routes.
  • Add all Route objects to the RouteCollection object.
  • Initialize the RequestContext object which holds the current request context information.
  • Initialize the UrlMatcher object by passing the RouteCollection object and the RequestContext object.

Initialize the Route Object for Different Routes

Let’s go ahead and define a pretty basic foo route.

The first argument of the Route constructor is the URI path, and the second argument is the array of custom attributes that you want to return when this particular route is matched. Typically, it would be a combination of the controller and method that you would like to call when this route is requested.

Next, let’s have a look at the parameterized route.

The above route can match URIs like foo/1, foo/123 and similar. Please note that we’ve restricted the {id} parameter to numeric values only, and hence it won’t match URIs like foo/bar since the {id} parameter is provided as a string.

Add All Route Objects to the RouteCollection Object

The next step is to add route objects that we’ve initialized in the previous section to the RouteCollection object.

As you can see, it’s pretty straightforward as you just need to use the add method of the RouteCollection object to add route objects. The first argument of the add method is the name of the route, and the second argument is the route object itself.

Initialize the RequestContext Object

Next, we need to initialize the RequestContext object, which holds the current request context information. We’ll need this object when we initialize the UrlMatcher object as we’ll go through it in a moment.

Initialize the UrlMatcher Object

Finally, we need to initialize the UrlMatcher object along with routes and context information.

Now, we have everything we could match our routes against.

How to Match Routes

It’s the match method of the UrlMatcher object which allows you to match any route against a set of predefined routes.

The match method takes the URI as its first argument and tries to match it against predefined routes. If the route is found, it returns custom attributes associated with that route. On the other hand, it throws the ResourceNotFoundException exception if there’s no route associated with the current URI.

In our case, we’ve provided the current URI by fetching it from the $context object. So, if you’re accessing the http://your-domain/basic_routes.php/foo URL, the $context->getPathInfo() returns foo, and we’ve already defined a route for the foo URI, so it should return us the following.

Now, let’s go ahead and test the parameterized route by accessing the http://your-domain/basic_routes.php/foo/123 URL.

It worked if you can see that the id parameter is bound with the appropriate value 123.

Next, let’s try to access a non-existent route like http://your-domain/basic_routes.php/unknown-route, and you should see the following message.

So that’s how you can find routes using the match method.

Apart from this, you could also use the Routing component to generate links in your application. Provided RouteCollection and RequestContext objects, the UrlGenerator allows you to build links for specific routes.

The first argument of the generate method is the route name, and the second argument is the array that may contain parameters if it’s the parameterized route. The above code should generate the /basic_routes.php/foo/123 URL.

Load Routes From the YAML File

In the previous section, we built our custom routes using the Route and RouteCollection objects. In fact, the Routing component offers different ways you could choose from to instantiate routes. You could choose from various loaders like YamlFileLoader, XmlFileLoader, and PhpFileLoader.

In this section, we’ll go through the YamlFileLoader loader to see how to load routes from the YAML file.

The Routes YAML File

Go ahead and create the routes.yaml file with the following contents.

An Example File

Next, go ahead and make the load_routes_from_yaml.php file with the following contents.

The only thing that’s different in this case is the way we initialize routes!

We’ve used the YamlFileLoader loader to load routes from the routes.yaml file instead of initializing it directly in the PHP itself. Apart from that, everything is the same and should produce the same results as that of the basic_routes.php file.

The All-in-One Router

Lastly in this section, we’ll go through the Router class, which allows you to set up routing quickly with fewer lines of code.

Go ahead and make the all_in_one_router.php file with the following contents.

Everything is pretty much the same, except that we’ve instantiated the Router object along with the necessary dependencies.

With that in place, you can straight away use the match method of the Router object for route mapping.

Also, you will need to use the getRouteCollection method of the Router object to fetch routes.

Conclusion

Go ahead and explore the other options available in the Routing component—I would love to hear your thoughts!

Today, we explored the Symfony Routing component, which makes implementation of routing in PHP applications a breeze. Along the way, we created a handful of examples to demonstrate various aspects of the Routing component. 

I hope that you’ve enjoyed this article, and feel free to post your thoughts using the feed below!


Source: Nettuts Web Development

Creating Pretty Popup Messages Using SweetAlert2

Every now and then, you will have to show an alert box to your users to let them know about an error or notification. The problem with the default alert boxes provided by browsers is that they are not very attractive. When you are creating a website with great color combinations and fancy animation to improve the browsing experience of your users, the unstyled alert boxes will seem out of place.

In this tutorial, you will learn about a library called SweetAlert2 that allows us to create all kinds of alert messages which can be customized to match the look and feel of our own website.

Display Simple Alert Messages

Before you can show all those sweet alert messages to your users, you will have to install the library and include it in your project. If you are using npm or bower, you can install it by running the following commands:

You can also get a CDN link for the latest version of the library and include it in your webpage using script tags:

Besides the JavaScript file, you will also have to load a CSS file which is used to style all the alert boxes created by the library:

Once you have installed the library, creating a sweet alert is actually very easy. All you have to do is call the swal() function. Just make sure that the function is called after the DOM has loaded.

There are two ways to create a sweet alert using the swal() function. You can either pass the title, body text and icon value in three different arguments or you can pass a single argument as an object with different values as its key-value pairs. Passing everything in an object is useful when you want to specify values for multiple arguments.

When a single argument is passed and it is a string, the sweet alert will only show a title and an OK button. Users will be able to click anywhere outside the alert or on the OK button in order to dismiss it.

When two arguments are passed, the first one becomes the title and the second one becomes the text inside the alert. You can also show an icon in the alert box by passing a third argument. This can have any of the five predefined values: warning, error, successinfo, and question. If you don’t pass the third argument, no icon will be shown inside the alert message.

Configuration Options to Customize Alerts

If you simply want to show some basic information inside an alert box, the previous example will do just fine. However, the library can actually do a lot more than just simply show users some text inside an alert message. You can change every aspect of these alert messages to suit your own needs.

We have already covered the title, the text, and the icons inside a sweet alert message. There is also an option to change the buttons inside it and control their behavior. By default, an alert will only have a single confirm button with text that says “OK”. You can change the text inside the confirm button by setting the value of the confirmButtonText property. If you also want to show a cancel button in your alert messages, all you have to do is set the value of showCancelButton to true. The text inside the cancel button can be changed using the cancelButtonText property.

Each of these buttons can be given a different background color using the confirmButtonColor and cancelButtonColor properties. The default color for the confirm button is #3085d6, while the default color for the cancel button is #aaa. If you want to apply any other customization on the confirm or cancel buttons, you can simply use the confirmButtonClass and cancelButtonClass properties to add a new class to them. Once the classes have been added, you will be able to use CSS to change the appearance of those buttons. You can also add a class on the main modal itself by using the customClass property.

If you interacted with the alert messages in the first example, you might have noticed that the modals can be closed by pressing either the Enter or Escape key. Similarly, you can also click anywhere outside the modal in order to dismiss it. This happens because the value of allowEnterKey, allowEscapeKey, and allowOutsideClick is set to true by default.

When you show two different buttons inside a modal, the confirm button is the one which is in focus by default. You can remove the focus from the confirm button by setting the value of focusConfirm to false. Similarly, you can also set the focus on the cancel button by setting the value of focusCancel to true.

The confirm button is always shown on the left side by default. You have the option to reverse the positions of the confirm and cancel buttons by setting the value of reverseButtons to true.

Besides changing the position and color of buttons inside the alert messages, you can also change the background and position of the alert message or the backdrop around it. Not only that, but the library also allows you to show your own custom icons or images in the alert messages. This can be helpful in a lot of situations.

You can customize the backdrop of a sweet alert using the backdrop property. This property accepts either a Boolean or a string as its value. By default, the backdrop of an alert message consists of mostly transparent gray color. You can hide it completely by setting the value of backdrop to false. Similarly, you can also show your own images in the background by setting the backdrop value as a string. In such cases, the whole value of the backdrop string is assigned to the CSS background property. The background of a sweet alert message can be controlled using the background property. All alert messages have a completely white background by default.

All the alert messages pop up at the center of the window by default. However, you can make them pop up from a different location using the position property. This property can have nine different values with self-explanatory names: top, top-start, top-end, center, center-start, center-end, bottom, bottom-start, and bottom-end.

You can disable the animation when a modal pops up by setting the value of the animation property to false. The library also provides a timer property which can be used to auto-close the timer once a specific number of milliseconds have passed.

In the following example, I have used different combinations of all the properties discussed in this section to create four different alert messages. This should demonstrate how you can completely change the appearance and behavior of a modal created by the SweetAlert2 library.

Important SweetAlert2 Methods

Initializing different sweet alert messages to show them to users is one thing, but sometimes you will also need access to methods which control the behavior of those alert messages after initialization. Fortunately, the SweetAlert2 library provides many methods that can be used to show or hide a modal as well as get its title, text, image, etc.

You can check if a modal is visible or hidden using the isVisible() method. You can also programmatically close an open modal by using the close() or closeModal() methods. If you happen to use the same set of properties for multiple alert messages during their initialization, you can simply call the setDefaults({configurationObject}) method in the beginning to set the value of all those properties at once. The library also provides a resetDefaults() method to reset all the properties to their default values.

You can get the title, content, and image of a modal using the getTitle(), getContent(), and getImage() methods. Similarly, you can also get the HTML that makes up the confirm and cancel buttons using the getConfirmButton() and getCancelButton() methods.

There are a lot of other methods which can be used to perform other tasks like programmatically clicking on the confirm or cancel buttons.

Final Thoughts

The SweetAlert2 library makes it very easy for developers to create custom alert messages to show to their users by simply setting the values of a few properties. This tutorial was aimed at covering the basics of this library so that you can create your own custom alert messages quickly. 

To prevent the post from getting too big, I have only covered the most commonly used methods and properties. If you want to read about all the other methods and properties which can be used to create advanced alert messages, you should go through the detailed documentation of the library.

Don’t forget to check out the other JavaScript resources we have available in the Envato Market, as well.

Feel free to let me know if there is anything that you would like me to clarify in this tutorial.


Source: Nettuts Web Development

Create Interactive Gradient Animations Using Granim.js

Gradients can instantly improve the look and feel of a website, if used carefully with the right color combination. CSS has also come a long way when it comes to applying a gradient on any element and animating it. In this tutorial, we will move away from CSS and create gradient animations using a JavaScript library called Granim.js.

This library draws and animates gradients on a given canvas according to the parameters you set when creating a Granim instance. There are different methods which can be used to make your gradient respond to different user events like a button click. In this tutorial, we will learn about this library in detail and create some simple but nice gradient animation effects.

Create Solid Color Gradient Animations

Before we begin creating any gradient, you will have to include the library in your project. For this, you can either download Granim.js from GitHub or link directly to a CDN. The library version that I am using in this tutorial is 1.1. Some methods that we will discuss here were only added in version 1.1, so using an older library version when following this tutorial will not always give the expected result. Keeping these points in mind, let’s create our first gradient using Granim.js.

Every time you create a new Granim instance, you can pass it an object of key-value pairs, where the key is the name of a particular property and the value is the value of the property. The element property is used to specify the CSS selector or DOM node which will point to the canvas on which you want to apply a particular gradient.

When you create a gradient animation where the colors change from a relatively light value to a darker value, it might become impossible to read some text that you have positioned on the canvas. For example, the initial gradient applied on an element might be a combination of yellow and light green. In such cases, the text of the canvas would have to be darker for users to be able to read it properly. 

Similarly, the gradient might consist of dark red and black at some other point, and in such cases the dark text would not be easy to read. Granim.js solves this problem for you by allowing you to specify a container element on which you can add the dark and light classes to style the text or other elements accordingly. The value of the elToSetClassOn property is set to body by default, but you can also specify any other container element. The dark and light class names are updated automatically based on the average color of the gradient.

The elToSetClassOn property does not work by itself. You will also have to specify a name for the Granim instance that you created using the name property. If you set the name to something like first-gradient, the name of the classes applied on the container element will become first-gradient-light or first-gradient-dark based on how light or dark the gradient currently is. This way, any element which needs to change its color based on the lightness or darkness of the gradient will be able to do so with ease.

The direction in which a gradient should be drawn can be specified using the direction property. It has four valid values: diagonal, left-right, top-bottom, and radial. The gradients that you create will not move in those particular directions—they will just be drawn that way. The position of the gradient doesn’t change during the animation; only its colors do.

There is also a states property, which accepts an object as its value. Each state specified inside the states object will have a name and a set of key-value pairs. You can use the gradients property to specify different colors which should make up a particular gradient. You can set the value of this property to be equal to an array of gradients. 

Granim.js will automatically create an animation where the colors of the gradient change from one set to another. The transition between different gradients takes 5,000 milliseconds by default. However, you can speed up or slow down the animation by setting an appropriate value for the transitionSpeed property.

After the gradients start animating, they will have to come to an end at one point or another. You can specify if the gradient should then just stop there or start animating again from the beginning using the loop property. This is set to true by default, which means that the gradient would keep animating.

Each color in a gradient can have a different opacity, which can be specified using the opacity property. This property accepts an array to determine how opaque each color is going to be. For two gradient colors, the value can be [0.1, 0.8]. For three gradient colors, the value can be [1, 0.5, 0.75], etc.

You also have the option to specify the time it takes for the gradient animation to go from one state to another using the stateTransitionSpeed. This is different from the transitionSpeed property, which controls the animation speed inside the same state.

In the following code snippet, I have created two different Granim instances to draw different gradients. In the first case, we have only specified a single gradient, so there is not any actual animation and the colors don’t change at all.

Animate Gradients Over an Image

Another common use of the Granim.js library would be to animate a gradient over an image drawn on the canvas. You can specify different properties to control how the image is drawn on the canvas using the image property. It accepts an object with key-value pairs as its value. You can use the source property to specify the path from which the library should get the image to draw it on the canvas.

Any image that you draw on the canvas will be drawn so that its center coincides with the center of the canvas. However, you can use the position property to specify a different position to draw the image. This property accepts an array of two elements as its value. The first element can have the values left, center, and right. The second element can have the values top, center, and bottom

These properties are generally useful when you know that the size of the canvas and the image won’t match. In these situations, you can use this property to specify the part of the image that should appear on the canvas.

If the images and the canvas have different dimensions, you can also stretch the image so that it fits properly inside the canvas. The stretchMode property also accepts an array of two elements as its value. Three valid values for both these elements are stretch, stretch-if-smaller, and stretch-if-larger.

A gradient with blend mode set to normal will completely hide the image underneath it. The only way to show an image below a gradient of solid colors would be to choose a different blend mode. You can read about all the possible blend mode values for a canvas on MDN.

I would like to point out that the ability to animate a gradient over an image was only added in version 1.1 of the Granim.js library. So you will have to use any version higher than that if you want this feature to work properly.

Methods to Control Gradient Animation Playback

Up to this point, we did not have any control over the playback of the gradient animation once it was instantiated. We could not pause/play it or change its state, direction, etc. The Granim.js library has different methods which let you accomplish all these tasks with ease.

You can play or pause any animation using the play() and pause() methods. Similarly, you can change the state of the gradient animation using the changeState('state-name') method. The state-name here has to be one of the state names that you defined when instantiating the Granim instance.

More methods were added in version 1.1 which allow you to change the direction and blend mode of an animation on the fly using the changeDirection('direction-name') and changeBlendingMode('blending-mode-name') methods.

In the following code snippet, I am using a button click event to call all these methods, but you can use any other event to call them.

Final Thoughts

In this tutorial, I have covered the basics of the Granim.js library so that you can get started with it as quickly as possible. There are a few other methods and properties that you might find useful when creating these gradient animations. You should read the official documentation in order to read about them all.

If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available in the Envato Market.

If you have any questions related to this tutorial, feel free to let me know in the comments.


Source: Nettuts Web Development

How to Build Complex, Large-Scale Vue.js Apps With Vuex

It’s so easy to learn and use Vue.js that anyone can build a simple application with that framework. Even novices, with the help of Vue’s documentation, can do the job. However, when complexity comes into play the things get a bit more serious. The truth is that multiple, deeply nested components with shared state can quickly turn your application into an unmaintainable mess.

The main problem in a complex application is how to manage the state between components without writing spaghetti code or producing side effects. In this tutorial you’ll learn how to solve that problem by using Vuex: a state management library for building complex Vue.js applications.

What is Vuex?

Vuex is a state management library specifically tuned for building complex, large-scale Vue.js applications. It uses a global, centralized store for all the components in an application taking advantage of its reactivity system for instant updates.

The Vuex store is designed in such a way that it is not possible to change its state from any component. This ensures that the state can only be mutated in a predictable manner. Thus your store becomes a single source of truth: every data element is only stored once and is read-only to prevent the application’s components from corrupting the state that is accessed by other components.

Why Do You Need Vuex?

You may ask: Why I need Vuex at first place? Can I just put the shared state in a regular JavaScript file and import it in my Vue.js application?

You can, of course, but compared to a plain global object Vuex store has some significant advantages and benefits:

  • The Vuex store is reactive. Once components retrieve a state from it, they will reactively update their views every time the state changes.
  • Components cannot directly mutate the store’s state. The only way to change the store’s state is by explicitly committing mutations. This ensures every state change leaves a trackable record which makes the application easier to debug and test.
  • You can easily debug your application thanks to the Vuex integration with Vue’s DevTools extension.
  • The Vuex store gives you a bird’s eye view on how everything is connected and affected in your application.
  • It’s easier to maintain and synchronize the state between multiple components, even if component hierarchy changes.
  • Vuex makes direct cross-components communication possible.
  • If some component is destroyed, the state in Vuex store will remain intact.

Getting Started With Vuex

Before we get started I want to make clear several things: First, to follow along this tutorial you need to have a good understanding of Vue.js and its components system, or at least minimal experience with the framework. 

Also, the aim of this tutorial is not to show you how to build actual complex application; the aim is to focus your attention more on Vuex concepts and how you can use it to build complex applications. For that reason, I’m going to use very plain and simple examples without any redundant code. Once you fully grasp the Vuex concepts you will be able to apply them on any level of complexity.

Finally, I’ll be using ES2015 syntax. If you are not familiar with it, you can learn it here.

And now, let’s get started!

Setting Up a Vuex Project

The first step to get started with Vuex is to have Vue.js and Vuex installed on your machine. There are several ways to do that but we’ll use the easiest one. Just create an HTML file and put the needed CDN links:

I use some CSS to make the components look nicer, but you don’t need to worry about that CSS code. It only helps you to gain a visual notion about what is going on. Just copy and paste the following inside the <head> tag:

Now, let’s create some components to work with. Inside the <script> tag, right above the closing </body> tag, put the following Vue code:

Here, we have a Vue instance, a parent component, and two child components. Each component have a heading “Score:” where we’ll output the app state.

The last thing you need to do is to put a wrapping <div> with id="app" right after the opening <body>, and then place the parent component inside:

So, the preparation work is done. We’re ready to move on.

Exploring Vuex

State Management

In real life we deal with complexity by using strategies to organize and structure the content we want to use. We group related things together in different sections, categories, etc. Just as how in a book library, the books are categorized and put in different sections so that we can easily find what we are looking for. The same is true for Vuex. It arranges the application data and logic related to state in four groups or categories: state, getters, mutations, and actions.

State and mutations are the base for any Vuex store:

  • state is an object that holds the state of the application data.
  • mutations is also an object containing methods which affect the state.

Getters and actions are like logical projections of state and mutations:

  • getters contains methods used to abstract the access to the state, and to do some preprocessing jobs, if needed (data calculating, filtering, etc.)
  • actions are methods used to trigger mutations and execute asynchronous code.

Let’s explore the following diagram to make the things a bit clear:

Vuex State Management Workflow Diagram

In the left side, we have an example of Vuex store, which we’ll create later on in this tutorial. In the right side, we have a Vuex workflow diagram, which shows how the different Vuex elements work together and communicate each another.

In order to change the state, a particular Vue component must commit mutations (eg. this.$store.commit('increment', 3)), and then, those mutations change the state (score becomes 3). After that, the getters are automatically updated thanks to Vue’s reactive system and they render the updates in the component’s view (with this.$store.getters.score). 

Mutations cannot execute asynchronous code, because this would make it impossible to record and track the changes in debug tools like Vue DevTools. To use asynchronous logic you need to put it in actions. In this case a component first will dispatch actions (this.$store.dispatch('incrementScore', 3000)) where the asynchronous code is executed, and then those actions will commit mutations, which will mutate the state. 

Create a Vuex Store Skeleton

After we explored how Vuex work, let’s create the skeleton for our Vuex store. Put the following code above the ChildB component registration:

To provide global access to the Vuex store from every component we need to add the store property in the Vue instance:

Now, we can access the store from every component with this.$store variable.

So far, if you open the project with CodePen in the browser, you should see the following result.

App Skeleton

State Properties

The state object contains all of the shared data in your application. Of course, if needed, each component can have its own private state too.

Imagine that you want to build a game application and you need a variable to store the game’s score. So, you put it in the state object:

Now, you can access the state’s score directly. Let’s go back to the components and reuse the data from the store. In order to be able to reuse reactive data from the store’s state, you should use computed properties. So, let’s create a score() computed property in the parent component:

In parent component’s template put the {{ score }} expression:

And now, do the same for the two child components.

Vuex is so smart that it will do all the work for us to reactively updates the score property whenever the state changes. Try to change the score’s value and see how the result updates in all of the three components.

Creating Getters

It is, of course, good that you can reuse the this.$store.state keyword inside the components, as you saw above. But imagine the following scenarios:

  1. In a large-scale application, where multiple components access the state of the store by using this.$store.state.score, you decide to change the name of score. This means that you have to change the name of the variable inside each and every component that uses it! 
  2. You want to use a computed value of the state. For example, let’s say you want to give the players a bonus of 10 points when the score reaches 100 points. So, when the score hits 100 points, 10 points bonus are added. This means each component has to contain a function that reuses the score and increment it with ten. You will have repeated code in each component, which is not good at all!

Fortunately, Vuex offers a working solution to handle such situations. Imagine the centralized getter that accesses the store’s state and provides a getter function to each of the state’s items. If needed, this getter can apply some computation to the state’s item. And if you need to change the name of some of the state’s properties, you only change them in one place, in this getter. 

Let’s create a score() getter:

A getter receives the state as its first argument, and then uses it to access the state’s properties.

Note: Getters also receive getters as the second argument. You can use it to access the other getters in the store.

In all components, modify the score() computed property to use the score() getter instead of state’s score directly.

Now, if you decide to change the score to result you need to update it only in one place: in the score() getter. Try it out in this CodePen!

Creating Mutations

Mutations are the only way allowed to change the state. Triggering changes simply means committing mutations in component methods.

A mutation is pretty much an event handler function that is defined by name. Mutation handler functions receive a state as a first argument. You can pass an additional second argument too, which is called the payload for the mutation. 

Let’s create a increment() mutation:

Mutations cannot be called directly! To perform a mutation, you should call the commit() method with a name of the corresponding mutation and possible additional parameters. It might be just one, as is the step in our case, or they might be multiple wrapped in an object.

Let’s use the increment() mutation in the two child components by creating a method named changeScore():

We are committing a mutation instead of changing this.$store.state.score directly, because we want to explicitly track the change made by the mutation. This way we make our application logic more transparent, traceable and easy to reason about. In addition, it makes it possible to implement tools, like Vue DevTools or Vuetron, that can log all mutations, take state snapshots, and perform time-travel debugging.

Now, let’s put the changeScore() method into use. In each template of the two child components, create a button and add a click event listener to it:

When you click the button, the state will be incremented by three, and this change will be reflected in all components. Now we have effectively achieved direct cross-components communication, which is not possible with the Vue.js built-in “props down, events up” mechanism. Check it out in our CodePen example.

Creating Actions

An action is just a function that commit a mutation. It changes the state indirectly which allows for executing of asynchronous operations. 

Let’s create a incrementScore() action:

Actions get the context as first parameter, which contains all methods and properties from the store. Usually we just extract the parts we need by using ES2015 argument destructing. The commit method is one we need very often. Actions also get a second payload argument, just like mutations.

In the ChildB component modify the changeScore() method:

To call an action we use dispatch() method with a name of the corresponding action and additional parameters just as with mutations.

Now, the “Change Score” button from ChildA component will increment the score by three. The identical button from ChildB component will do the same, but after 3 seconds delay. In the first case we execute synchronous code and we use a mutation, but in the second case we execute asynchronous code and we need to use an action instead. See how it all works in our CodePen example.

Vuex Mapping Helpers

Vuex offers some useful helpers which can streamline the process of creating state, getters, mutations, and actions. Instead of writing those functions manually we can tell Vuex to create them for us. Let’s see how it works.

Instead of writing the score() computed property like this:

We just use the mapState() helper like this:

And the score() property is created automatically for us.

The same is true for the getters, mutations, and actions. 

To create the score() getter we use mapGetters() helper:

To create changeScore() method we use mapMutations() helper like this:

When used for mutations and actions with payload argument, we must pass that argument in the template where we define the event handler:

If we want changeScore() to use an action instead of a mutation we use mapActions() like this:

Again, we must define the delay in the event handler:

Note: All mapping helpers return an object. So, if we want to use them in combination with other local computed properties or methods we need to merge them into one object. Fortunately with the object spread operator (...)  we can do it without using any utility. 

In our CodePen you can see an example of how all mapping helpers are used in practice.

Making the Store More Modular

It seems that the problem with complexity constantly obstructs our way. We solved it before by creating Vuex store, where we made the state management and components communication easy. In that store we have everything in one place, easy to manipulate and easy to reason about. However, as our application grows this easy to manage store file becomes larger and larger, and, as a result, harder to maintain. Again, we need some strategies and techniques for improving the application structure by returning it to its easy to maintain form. In this section, we’ll explore several techniques which can help us in this undertaking.

Using Vuex Modules

Vuex allows us to split the store object into separate modules. Each module can contain its own state, mutations, actions, getters, and other nested modules. After we create the needed modules, we register them in the store.

Let’s see it in action:

In the above example, we created two modules, one for each child component. The modules are just plain objects, which we register as scoreBoard and resultBoard in the modules object inside the store. The code for childA is the same as that in the store from the previous examples. In the code for childB we add some changes in values and names.

Let’s now tweak ChildB component to reflect the changes in the resultBoard module. 

In ChildA component the only thing we need to modify is the changeScore() method:

As you can see, splitting the store into modules makes it much more lightweight and maintainable, while still keeps its great functionality. Check out the updated CodePen to see it in action.

Namespaced Modules

If you want or need to use one and the same name for particular property or method in your modules, then you should consider namespacing them. Otherwise you may observe some strange side effects, such as executing all the actions with same names, or getting the wrong state’s values. 

To namespace a Vuex module you just set the namespaced property to true.

In the above example we made the property and method names the same for the two modules. And now we can use a property or method prefixed with the name of the module. For example, if we want to use the score() getter from the resultBoard module, we type it like this: resultBoard/score. If we want the score() getter from the scoreBoard module, then we type it like this: scoreBoard/score

Let’s now modify our components to reflect the changes we made. 

As you can see in our CodePen example, we can now use the method or property we want and get the result we expect.

Splitting the Vuex Store Into Separate Files

In the previous section, we improved the application structure to some extent by separating the store into modules. We made the store cleaner and more organized, but still all of the store code and its modules lie in one and the same big file. 

So the next logical step is to split the Vuex store in separate files. The idea is to have an individual file for the store itself and one for each of its objects, including the modules. This means having separate files for the state, getters, mutations, actions, and for each individual module (store.jsstate.js, getters.js, etc.) You can see an example of this structure at the end of the next section.

Using Vue Single File Components

We’ve made the Vuex store as modular as we can. The next thing we can do is to apply the same strategy to the Vue.js components too. We can put each component in a single, self-contained file with a .vue extension. To learn how this works you can visit the Vue Single File Components documentation page

So, in our case, we’ll have three files: Parent.vueChildA.vue, and ChildB.vue

Finally, if we combine all three techniques we’ll end up with the following or similar structure:

In our tutorial GitHub repo you can see the completed project with the above structure.

Recap

Let’s recap some main points you need to remember about Vuex:

Vuex is a state management library, which help us to build complex, large-scale applications. It uses a global, centralized store for all the components in an application. To abstract the state we use getters. Getters are pretty much like computed properties and are ideal solution when we need to filter or calculate something on runtime.

Vuex store is reactive and components cannot directly mutate the store’s state. The only way to mutate the state is by commiting mutations, which are synchronous transactions. Each mutation should perform only one action, must be as simple as possible, and only responsible for updating just a piece of state.

Asynchronous logic should be encapsulated in actions. Each action can commit one or more mutations, and one mutation can be committed by more than one action. Actions can be complex but they never change the state directly.

Finally, modularity is the key to maintainability. To deal with complexity and make our code modular we use the “divide and conquer” principle and the code splitting technique.

Conclusion

So folks, that’s it. You already know the main concepts behind Vuex and you are ready to start applying them in practice.  

For the sake of brevity and simplicity, I omitted intentionally some details and features of Vuex, so you’ll need to read the full Vuex documentation to learn everything about Vuex and its feature set.


Source: Nettuts Web Development