Article Objective
At the end of this technical article, the reader will have learned about filter (a JavaScript array method), its practical use on a website, and how to implement filter in ReactJS to display a specific content or set of contents on any website.
Introduction
A filter, as the name suggests, is a function that is being used on most websites to sort out specific user preferences. You must have used a filter on an e-commerce website when shopping for a specific product out of the multitude of similar products. The way filter is implemented on many websites is different. On some websites, you can search for a product and then you get the filtered results. On some other websites, you can hit a button for a particular product and you will only get a variety of that product.
In this technical article, we will be implementing a product filter in ReactJS in which when the button for a particular laptop brand (which can be any product) is clicked or tapped, only the available products of that laptop brand will be displayed out of all the laptop brands.
Prerequisites
You must have Node.js installed on your computer
Have some working knowledge of ReactJS
Have a good understanding of HTML, CSS, and JavaScript
Have a basic understanding of DOM
Step 1: Getting Started with React
Fundamental React concepts:
Creating React application
Components
JSX
Objects
Filter
Installation and Setup
To create our React application, we are going to be making use of Vite.
The regular create-react-app command is what many developers have used to set up and configure their React projects over the years. However, Vite is a modern and better alternative in the sense that its development times is quite fast and it offers better performance.
Open your code editor (if you're using VS Code) and go to Terminal → New Terminal or you can type Ctrl+Shift+` on the VS Code welcome page to open a new terminal.
Start by typing the following command on your terminal:
npm create vite@latest
Hit enter
Enter y and hit enter. It will ask you for “Project name”. You can hit enter and continue with the default name (vite-project) or rename it.
You will then be provided with the option to pick a framework
Use the arrow down key on your PC to select React and hit enter. Next, it will require you to choose between TypeScript and JavaScript. Select JavaScript and hit enter.
Now run the following commands one after the other to finish setting up your React project:
After all the packages have been installed, you should see the following:
Hit Ctrl + Enter on the link provided and it will open in your default browser
Good job if your browser displays the above. Now let’s do a bit of tidying up in our React project folders.
Inside src (source folder), do the following:
Delete assets (it contains a React SVG file that is not needed).
Delete App.css – it is not needed here.
Inside index.css, delete everything; we are going to define our styles.
After doing all of these, you should have your project folder looking like this:
Inside index.html, first, delete the link to the Vite SVG logo. Then you can rename the title of your web app from “Vite + React” to any title you like inside index.html – this project is titled “Product Filter in React”.
Having done all these, let’s move on to the next step.
Step 2: Using a background-image
What we are going to do here is pretty straightforward – we are going to add a background image to the body of our web project using CSS (under index.css).
So this is how the body of our web project now looks:
Step 3: Creating Components and Needed Files
React is component-based, meaning everything you interact with on a React web app is a component. So we are going to create all the components we need here.
In src, create a folder named “Components”. Inside this new folder, create two files: Cards.jsx and Navbar.jsx
Also, in src, create another folder named “Images” – this folder is going to contain all the images to be used.
To add images here, you can either copy and cut the images to the “Images” folder of your project folder (on your PC) or copy and cut the images from the root folder of your project to “Images” under src in your VS Code.
Note: You have to rename the images to only have one name. Each image shouldn’t contain any spaces or have more than one name.
The background image and laptop images used for this project can be freely downloaded online. You can choose to download and use any image of your choice.
We then need to add a JavaScript file, object.js, to the src.
After adding these components and files, our React project folder is going to look like this:
Step 4: Navbar.jsx
This is where we write the content of the navbar and it’s a simple one. We are just going to write “React Product Filter” here.
Inside Navbar.jsx, type rfce and then write “React Product Filter”.
Step 5: Objects.js
Inside Objects.js, we are going to create six objects. These objects are the specifications of different laptop brands. But before we create these objects, we want to import the laptop images that will represent each object and this is how to do it:
Now that the images are imported into Objects.js, we can proceed to create the six objects that are going to bear laptop specifications for different brands. We are going to be using a JavaScript concept to do this and here is how:
export const laptop_brand = [
{
Name:"Apple", Model: "MacBook Pro", Processor:"M2 Pro", Gen: "2nd", RAM: "16GB",
img: picture1,
SSD: "512GB", Screensize: "14 inches", Backup: "22 hours"
},
{
Name:"Dell", Model: "Inspiron 14", Processor:"Intel Core i5", Gen: "11th", RAM:"16GB",
img: picture2,
SSD: "512GB", Screensize: "14 inches", Backup: "13 hours",
},
{
Name:"HP", Model: "Spectre", Processor:"Intel Core i5", Gen: "10th", RAM:"8GB",
img: picture3,
SSD: "256GB", Screensize: "14.1 inches", Backup: "14 hours"
},
{
Name:"Lenovo", Model: "Yoga", Processor:"Intel Core i7", Gen: "10th", RAM:"16GB",
img: picture4,
SSD: "512GB", Screensize: "13.3 inches", Backup: "17 hours"
},
{
Name:"Dell", Model: "XPS 15", Processor:"Intel Core i7", Gen: "10th", RAM:"16GB",
img: picture5,
SSD: "512GB", Screensize: "15.6 inches", Backup: "16 hours",
},
{
Name:"HP", Model: "Omen", Processor:"Intel Core i7", Gen: "10th", RAM:"16GB",
img: picture6,
SSD: "512GB", Screensize: "15.6 inches", Backup: "15 hours"
},]
As you can notice, there are two objects apiece for the Dell and HP brands, as well as one object apiece for the Apple and Lenovo brands. So when the filter is implemented, the corresponding object(s) for each laptop brand will be displayed.
Step 6: Card.jsx
Inside card.jsx, we are going to declare a function under which:
The filter function is going to be defined and this will filter out the laptop brands as “All”, “Apple”, “Dell”, “HP”, and “Lenovo”.
So by default, the webpage will open to “All” which contains all the laptop brands. But when a user click or tap on, let’s say, "Apple”, all available Apple laptops will be shown; the same thing applies to the other laptop brands.
A return is going to be defined to return the corresponding card(s) that contain the specifications of the different laptop brands.
The following are the lines of code we need to write in card.jsx:
// eslint-disable-next-line no-unused-vars
import React, {useState} from 'react'
import {laptop_brand} from '../Objects'
function Cards() {
const [filterdata,setfilterdata] = useState(laptop_brand)
function filter_brand(data)
{
var dataFilter = laptop_brand.filter((fdata)=>{
if(data === 'all')
{
return fdata
}
else if(data === 'apple')
{
return fdata.Name === 'Apple'
}
else if(data === 'dell')
{
return fdata.Name === 'Dell'
}
else if(data === 'hp')
{
return fdata.Name === 'HP'
}
else if(data === 'lenovo')
{
return fdata.Name === 'Lenovo'
}
else
{
return fdata
}
})
setfilterdata(dataFilter)
console.log(filterdata)
}
return (
<div>
<ul className='navbar-items'>
<li className="all" onClick={() => filter_brand('all')}>All</li>
<li className="apple" onClick={() => filter_brand('apple')}>Apple</li>
<li className="dell" onClick={() => filter_brand('dell')}> Dell</li>
<li className="hp" onClick={() => filter_brand('hp')}>HP</li>
<li className="lenovo" onClick={() => filter_brand('lenovo')}>Lenovo</li>
</ul>
<div className="specs-container">{
filterdata.map((mydata)=>{
return <>
<div className="card">
<img src={mydata.img} alt="" className='display-image' height='120px' width='100%'/>
<ul className='spec-items'>
<li className='list-border'>Laptop name: {mydata.Name}</li>
<li className='list-border'>Model: {mydata.Model} </li>
<li className='list-border'>Processor: {mydata.Processor}</li>
<li className='list-border'>Generation: {mydata.Gen}</li>
<li className='list-border'>RAM: {mydata.RAM}</li>
<li className='list-border'>ROM: {mydata.SSD}</li>
<li className='list-border'>Backup: {mydata.Backup}</li>
</ul>
<button>Buy</button>
</div>
</>
})}
</div>
</div>
)}
export default Cards
With these, our React product filter is fully functional and is now able to filter all the laptop brands and only show a specific laptop brand and its specifications. But no styles have been applied yet to give our project a nice interface.
You’ll notice that the containers and elements defined above all have className. This is done so that the cards and the specifications they bear can be styled inside index.css.
Step 7: Adding CSS Styles
Using all the className specified above, let’s apply the following CSS styles inside index.css to give our web project a nice interface and make it responsive:
nav h2
{
color: white;
}
.navbar-items
{
width: 85%;
height: 30px;
margin: auto;
list-style: none;
padding: 5px;
display: flex;
justify-content: center;
gap: 30px;
color: white;
background-color: #008b8b;
line-height: 30px;
border-radius: 5px;
}
.navbar-items li:hover
{
width: 70px;
height: fit-content;
border-radius: 20px;
background: linear-gradient(to right, #7fff00, #ff6200);
box-shadow: 3px 3px #000000;
text-align: center;
cursor: pointer;
}
.specs-container
{
width: 90%;
height: fit-content;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 15px;
margin: auto;
margin-top: 30px;
padding: 0px;
overflow: hidden;
}
.card
{
width: 220px;
height: 320px;
margin: auto;
background-color: #ff6200;
border-radius: 7px;
}
.display-image
{
border-radius: 7px 7px 0px 0px;
}
ul
{
list-style: none;
font-size: 14px;
}
.spec-items
{
color: #ffffff;
padding: 0px;
}
.list-border
{
border-left: 5px solid #008b8b;
padding: 1px;
margin: 2px;
}
button
{
width: 80%;
position: relative;
left: 9.5%;
border-radius: 5px;
background-color: #9acd32;
padding: 4px;
}
Step 8: Final Outputs
After applying all the CSS styles above, our React product filter is finally going to look this way:
As you can see from the image above, the filter displays all the available laptop brands. To see the quantities under each brand, a user has to click on a specific brand.
Let’s say a user wants to see how many HP laptops are available, this is what the user will be shown:
Also, if a user wants to see how many Apple laptops are available, below is what the user will be shown:
If a buyer also clicks or taps on the other laptop brands (Dell and Lenovo), only the quantities available under them will be shown to the buyer.
Summary
Filter makes sorting out products or items based on user preferences easy. A filter can be used to group or categorize the different types or varieties of available products, which effectively helps users or buyers narrow down their choices when purchasing a product from a website. In this beginner's guide, we have been able to see how a filter (a JavaScript array method) works and how it is implemented in ReactJS.
Thanks for reading!