Web Analytics
  • Culture
      Back
      Agile Mindset

      Agile is not a principal or a method, but it’s an integral part of being Agile that is guided by principles, defined by values and manifested through various practices.

      Bacancy Values

      You add value to your customer when you deliver a product or service that has been designed specifically to solve their problem.

      Bacancy Culture

      Core Team will work as Scrum Team where Team will have quarterly goal to make sure that we run financial, administrative and project management prospective.

  • What we do
      Back
      Product Engineering

      Seize the opportunity to make your product stand out. We enable our clients

      AI & ML

      We automate businesses and optimize processes by deploying smart AI and...

      Blockchain

      Get a full spectrum of blockchain development services from us to bring scalability...

      IOT

      Improve Business Productivity and Efficiency using our high-end IOT professional services...

      Digital Transformation

      We truly become a part of your business by helping you think through the...

  • Who we work with
      Back
      Real Estate

      We can help you uncover the hidden revenue opportunities to showcase your...

      Finance & Insurance

      In the emerging technological environment, we are offering reliable banking and financial...

      Oil & Gas

      Reshape your energy landscape and gain better control by harnessing the best...

      Healthcare

      Utilizing advanced technologies to provide best software, web & mobile development services...

      Travel & Transport

      Manage your logistics and transportation business at the ease of your fingertips...

      Startups

      We can help you to build your MVP with advanced technologies....

  • About Us
      Back
      About

      Agile, A Process Delivering Values & Successful Products

      Blog

      Abstract Technology News Driven by Sources

      Career

      If you are passionate about your career, have creative flair and good craft skills, we want you!

  • Technology
      Back

      Front-End

      AngularJS ReactJS Vue.JS JavaScript Backbone.JS Ember.JS MEAN MERN

      Back-End

      Ruby on Rails Node.JS Golang Laravel PHP Python .NET Yii

      Mobile

      Android iOS React Native Flutter Ionic Kotlin

      CMS & CRM

      Spree Magento Wordpress Drupal Umbraco Woocommerce Salesforce Microsoft Dynamics 365<
      Explore All
  • Talk to Us
Talk to Us
Close
    MENU
  • Culture
    • Agile Mindset
    • Bacancy Values
    • Bacancy Culture
  • What we do
    • Product Engineering
    • AI & ML
    • Blockchain
    • IOT
    • Digital Transformation
  • Who we work with
    • Real Estate
    • Finance & Insurance
    • Oil & Gas
    • Healthcare
    • Travel & Transport
    • Startups
  • About Us
    • About
    • Blog
    • Career
  • Technology
      Front-End
    • AngularJS
    • ReactJS
    • Vue.JS
    • JavaScript
    • Backbone.JS
    • Ember.JS
    • MEAN
    • MERN
    • Back-End
    • Ruby on Rails
    • Node.JS
    • Golang
    • Laravel
    • PHP
    • Python
    • .NET
    • Yii
    • Mobile
    • Android
    • iOS
    • React Native
    • Flutter
    • Ionic
    • Kotlin
    • CMS & CRM
    • Spree
    • Magento
    • Wordpress
    • Drupal
    • Umbraco
    • Woocommerce
    • Salesforce
    • Microsoft Dynamics 365
    • Explore All
  • Contact Us
  • CLOSE
React Filter Component

A Comprehensive Guide on Developing Responsive and Common React Filter Component

Archita Nayak
Archita Nayak Technical Writer
January 20, 2021 7 min read

Last Updated on March 3, 2021

Your end-users always expect the UI to be more consistent, comfortable, and attractive in web and mobile applications. With that consideration, the product should be developed, keeping the user interface’s consistency in their minds. This task can be challenging when there’s a need for a responsive website for different screen widths and layouts. So, I have come up with this blog that will help you build a Responsive React Filter Component. Without much ado, let’s start coding.

Table of Index

1. User Interface for Responsive React Filter Component

2. Steps for building React Filter Component:

  • Building a Button controlling React Filter Component
  • Design of the Button using CSS
  • Use of Ref and useEffect
  • Implementing Modal for Mobile Devices using Reach UI
  • Putting all the pieces together

3. Conclusion

User Interface for Responsive React Filter Component

Before discussing how to build a responsive React Filter Component, let’s see the UI and its use case. So, here is the mockup of the component that we are going to build. The main idea of it is – on clicking the button named JS Frameworks, a dropdown will be displayed for web applications, and for mobile applications, it will cover the entire screen. I hope you have understood the UI, structure, and need.

Responsive React Filter Component

Steps for building React Filter Component

As we discussed earlier, we wanted to build a component that satisfies various screen widths. Thus, I would create one common component for this filter, which would decide which component should be displayed depending on different screen widths. But, before that, we need to do a lot more code. For simplifying it, I have divided it into five parts, maintaining the flow to code at ease.

Hire React.js Developer USA

Building a Button controlling React Filter Component

In the first step, I will implement a Button having the state value for opening and closing the filter. I have also given a basic styling to the button to make it look good; you can change the design at your convenience.

// FilterComponent.js

import React, { useState } from 'react';
import './FilterComponent.css';
‍
function FilterComponent() {
 // Declaring a new state variable named "isOpen"
 const [isOpen, setIsOpen] = useState(false);
 
 return (
   < div className="filter_wrapper" >
     < button
       onClick={() => setIsOpen(!isOpen)}
       className="filter_button"
     >
       JS Frameworks
     < /button >
   < /div >
 );
}

Design of the Button using CSS

// FilterComponent.css

.filter_wrapper {
 position: relative;
 display: inline-block;
}
.filter_button {
 border-radius: 5px;
 padding: 8px 16px;
 background-color: #408aeb;
 cursor: pointer;
 font-weight: 500;
 color: white;
 font-size: 18px;
 line-height: 1.5;
}
.filter_button:hover {
 background-color: #092b58;
}
.filter_button:focus {
 outline: 1px dashed;
 outline: 1px auto -webkit-focus-ring-color;
}

Use of Ref and useEffect

So far, we have made our React Filter component and styled it with a basic design. One more thing to be done is whenever users click outside an opened dropdown; they would expect the dropdown to be closed. For that, I will use the Ref and useEffect.

useEffect(() => {
   const handleClick = event => {
     const isDropdownClicked =
       dropdownRef.current && dropdownRef.current.contains(event.target);
     const isButtonClicked =
       buttonRef.current && buttonRef.current.contains(event.target);
 
     
if (isDropdownClicked || isButtonClicked) {
       // We would do nothing if the ref is undefined or the user clicks on the menu.
       return;
     }
     // Or else close the menu.
     setIsOpen(false);
   };
    
     document.addEventListener("mousedown", handleClick); 
     document.addEventListener("touchstart", handleClick); 
 
   // cleanup
   return () => {
     document.removeEventListener("mousedown", handleClick);  
     document.removeEventListener("touchstart", handleClick);   
   };
 }, [dropdownRef, buttonRef]);

Tip – You can use a custom user hook, useClickOutside, and write your logic of useEffect there to avoid cluttering in your component.

Let’s have a glance at our component. So far, so good!

Building responsive filter component

Now further, we need to implement this for mobile devices.

Implementing the Modal for Mobile Devices using Reach UI

The concept of modal might simple- to cover the entire screen with the title at the top. But, when it comes to implement and start coding, believe me, it can be challenging. We would be using Reach UI for managing focus states, semantics, and other difficulties related to the modal components. You can prefer any library which has a Modal component; it’s totally up to your choice. Since I’m familiar with Reach UI, I would go with that.

I’ll create a component – FilterModalComponent, that would contain my Modal. And later, I’ll import this into my FilterComponent.

// FilterModalComponent.js

import React from "react";
import { DialogOverlay } from "@reach/dialog";
‍import "./FilterModalComponent.css";
 
const FilterModalComponent = React.forwardRef(‍
 ({ children, onSelect, onCancel }, ref) => {
   return (
    < div className="modal_wrapper" >
     < DialogOverlay
       ref={ref}
       className="modal_container"
       aria-label="modal window"
     >
       < div className="modal_header" >
         < button onClick={() => onCancel()} >x< /button >
       < /div >
       < div className="modal_content" >{children}< /div >
       < div className="modal_actions" >
         < button onClick={() => onSelect()} >Select< /button >
       < /div >
     < /DialogOverlay >
    < /div >
   );
 });
export default FilterModal;

And the CSS file of FilterModal is here –

// FilterModalComponent.css

.modal_wrapper {
 display: block;
 background-color: transparent;
}
 
 
@media (min-width: 768px) {
 .modal_wrapper {
   display: none;
 }
}
 
.modal_container {
 z-index: 60;
 display: flex;
 background-color: white;
 right: 0;
 flex-direction: column;
 position: fixed;
 top: 5px;
}
 
.modal_header {
 padding: 20px 12px;
 border-bottom-color: #e4e6eb;
 display: flex;
 border-bottom-width: 10px;
}
 
.modal_content {
 display: flex;
}
 
.modal_actions {
 display: flex;
 align-items: center;
 border-top-width: 3px;
 justify-content: flex-end;
 margin-top: 5px;
 border-top-color: #e4e7eb;
 padding: 8px;
}
 
.modal_actions button {
 font-weight: 500;
 border-radius: 2px;
 padding: 5px 8px;
 cursor: pointer;
 background-color: #2b7de9;
 width: auto;
 color: white;
}

Our Filter Modal component is ready, which will only appear for small screens because of this –

@media (min-width: 768px) {
 .modal_wrapper {
   display: none;
 }
}

This is how our component will look like.

our component

Now, it’s time to import this FilterModalComponent into the FilterComponent. Keep in mind that modal expects Ref to prevent it from closing unexpectedly, and other props like – onSelect and onCancel, for controlling the user’s actions.

import React, { useState, useRef, useEffect } from "react";
import "./FilterComponent.css";
‍import FilterModalComponent from "./FilterModalComponent";
 
export default function FilterComponent() {
 const [isOpen, setIsOpen] = useState(false);
 const dropdownRef = useRef(undefined);
 const buttonRef = useRef(undefined);
 const modalRef = useRef(undefined);
 
useEffect(() => {
 const handleClick = event => {
 
const isDropdownClicked = dropdownRef.current && dropdownRef.current.contains(event.target);
 const isButtonClicked = buttonRef.current && buttonRef.current.contains(event.target);
 const isModalClicked = modalRef.current && modalRef.current.contains(event.target);
 
 if (isDropdownClicked || isButtonClicked || isModalClicked) {
  // We would do nothing if the ref is undefined or user clicks on menu.
   return;
 }
 
 // Or else close the menu.  
 setIsOpen(false);
 };
 
 document.addEventListener("mousedown", handleClick);
 document.addEventListener("touchstart", handleClick); 
 
 // cleanup
 return () => {
   document.removeEventListener("mousedown", handleClick);
   document.removeEventListener("touchstart", handleClick);
 };
}, [dropdownRef, buttonRef, modalRef]);
‍
const handleSelect = () => {‍
 alert("Yay! Filters applied!");‍
 setIsOpen(false);
‍};
 
return (
 < div className="filter_wrapper" > 
   < button 
     ref={buttonRef}
     onClick={() => setIsOpen(!isOpen)}
     className="filter_button"
   >
     JS Frameworks
  < /button >
‍   {isOpen && (
   < div ref={dropdownRef} className="filter_dropdown" >
‍     < div >
‍       Dropdown content goes here
‍       < div className="filter_dropdown_actions" >
‍         < button onClick={() => handleSelect()}      className="filter_dropdown_button" >
         Select
        < /button >
      < /div >
    < /div >
  < /div >
)}
      
 {isOpen && (
   < FilterModalComponent
‍     ref={modalRef}
     onSelect={() => handleSelect()}
     onCancel={() => setIsOpen(false)}
   >
    Modal content goes here.
‍   < /FilterModalComponent >
  )}
‍  < /div >
 );
}

Putting all the pieces together

Now, it’s time to give actual user inputs and see how it works. We are going to implement multiple select filters from which users can choose the JS framework.

import React, { useState } from "react";
‍import "./main.css";
‍import FilterComponent from "./FilterComponent";
 
const frameworks = ["ReactJS", "AngularJS", "VueJS", "NodeJS", "EmberJS"];
 
export default function DemoApp() {
‍
 const [selectedFrameworks, setSelectedFrameworks] = useState([]);
 
 const handleSelect = framework => {
   const isSelected = selectedFrameworks.includes(framework);
   const newSelection = isSelected
   ? selectedFrameworks.filter(currentTech => currentTech !== framework)
   : [...selectedFrameworks, framework];
   setSelectedFrameworks(newSelection);};
 
return (
 < div className="app_container" >
   < h2 >Building responsive filter component< /h2 >
   < FilterComponent
      label="JS Frameworks" 
      onSelect={() => alert(selectedFrameworks)}
    >
‍     < div className="frameworks-list" >
       {frameworks.map((framework, index) => {
         const isSelected = selectedFrameworks.includes(framework);
         return (
           < label key={index} >
             < input
               type="checkbox"
               checked={isSelected}
               onChange={() => handleSelect(framework)}
             / >
‍             < span className="ml-2 text-base text-gray-500 font-heading" >
‍               {framework}
‍             < /span >
           < /label >   
           ); 
         })}
     < /div >
‍     < /FilterComponent >
 < /div >
 );
}

This is how our Filter component with checkboxes of JS frameworks looks like –

 Filter component

And on mobile screens –

mobile screens

Conclusion

So, this was about how to build a responsive filter component. I hope you are pretty clear about its implementation. If you are looking for any development support regarding ReactJS development, then Bacancy Technology is a one-stop solution to hire dedicated ReactJS developers to build an optimal product.

Archita Nayak
Archita Nayak View all post
Writer. Developer. Dreamer. Believer. Achiever. My curiosity leads me to learn various technologies, and my love for writing helps me to impart my knowledge for the same. When I am not exploring technologies, I am mostly reading and writing poetry and fictional stories.

Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : [email protected]

Your Success Is Guaranteed !


Related articles
Dockerize React App
DockerReact JS
Here’s How to Dockerize React App [Containerize React App]
February 17, 2021 by: Archita Nayak
React Router Hooks
React JS
A Beginner’s Guide to React Router Hooks (Fundamentals of Routing in React)
December 18, 2020 by: Archita Nayak
ReactJS for Dashboards and Data Visualization
React JS
ReactJS for Dashboards and Data Visualization: An Exceptional Choice
November 18, 2020 by: Paridhi Wadhwani

Top 1% IT Talent

Bacancy Technology is an exclusive hub of top dedicated software developers, UI/UX designers, QA experts, and product managers with an incredibly rare and hidden talents you will ever come across. We let you access the top 1% IT talent from independent software developers to the fully managed teams.

Time Zone Aligned

Timezone is never a constraint when you are working with Bacancy Technology. We follow one very simple principle – our developers and your time zone. Hire dedicated software developers from us and make collaboration in a faraway to work according to your time zone, deadline, and milestone.

Experienced Team

Whether you are looking for skilled developers in emerging technologies or looking for an extended arms to augment your existing team, we can lend a helping hand in both situations. We are a full-stack software development company with 300+ skilled and experienced software developers whom you can hire at your convenience to address the ongoing business challenges

Let us help you build a modern digital business to overcome traditional culture and succeed in the age of digital transformation.

  • USA
  • Canada
  • Australia
  • India
  • UAE
  • Sweden

USA

Bacancy Technology LLC

Florida

4995 NW 72nd Ave, Suite 307 Miami, FL 33166

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Canada

Bacancy Technology Inc

Toronto

71 Dawes Road, Brampton, On L6X 5N9, Toronto

Phone

+1 416 907 6738

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Australia

Bacancy Technology

South Australia

351A Hampstead Rd, Northfield SA 5085

Phone

(02) 8005 8222

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

India

Bacancy Technology Pvt Ltd

Ahmedabad

1207-1210, Time Square, Thaltej-Shilaj Road, Ahmedabad

Pune

2nd Floor, Marisoft-1, Marigold IT Park, Pune

Phone

079- 40037674

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

UAE

Bacancy Technology

Dubai

1608 Clover Bay, Business Bay, Dubai, UAE. PO Box 62049

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Sweden

Bacancy Technology

Hagersten

Junkergatan 4, 126 53 Hagersten

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

How Can We Help?

  • Employee
  • Brochure
  • Quality Assurance
  • Resources
  • Privacy Policy
  • Sitemap
  • Solution
  • Contact Us
DMCA.com Protection Status
Request A Free Consultation