<div className="col-md-4"> <select className="form-select"… · The Chat Archive
To make the dropdown searchable, you can use a library like React Select, which provides a rich selection component with built-in search functionality. Here's an example of how you could transform your existing code to use React Select:
Install the react-select package:
bash Copy code
npm install react-select
Update your component to use ReactSelect:
jsx Copy code
import React from 'react';
import Select from 'react-select';
const MyComponent = ({ selectedTag, setSelectedTag, categories }) => {
// Map categories to the format required by react-select
const options = [
{ value: 'all', label: 'All' },
...categories.map(tag => ({ value: tag.value, label: tag.label })),
];
// Find the selected option to ensure the current selection is displayed correctly
const selectedOption = options.find(option => option.value === selectedTag);
return (
<div className="col-md-4">
<Select
className="form-select"
styles={{
control: (base) => ({
...base,
backgroundColor: "#333333",
color: "#ffffff",
}),
singleValue: (base) => ({
...base,
color: "#ffffff",
}),
menu: (base) => ({
...base,
backgroundColor: "#333333",
}),
option: (base, state) => ({
...base,
backgroundColor: state.isSelected ? "#666666" : "#333333",
color: "#ffffff",
'&:hover': {
backgroundColor: "#555555",
},
}),
}}
value={selectedOption}
onChange={(option) => setSelectedTag(option.value)}
options={options}
isSearchable={true}
/>
</div>
);
};
export default MyComponent;
In this implementation:
We import Select from react-select and replace the standard HTML select element with it.
We prepare the categories in the format expected by react-select, which is an array of objects with value and label properties.
We use the styles prop of react-select to customize the appearance, aligning it with your specified styles.
The isSearchable prop is set to true to enable search functionality.
This setup should provide you with a searchable dropdown that closely matches the style of your original component.
import React, { useState, useEffect } from "react";
import PageBanner from "../../components/general/PageBanner";
import { getCampaigns, getTags } from "../../api";
import FundraiseCard from "../../components/general/FundraiseCard";
function CampaignsPage() {
const [campaigns, setCampaigns] = useState([]);
const [filteredCampaigns, setFilteredCampaigns] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 8; // Adjust items per page as needed
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const [selectedTag, setSelectedTag] = useState("all");
const [sortOption, setSortOption] = useState("none");
const [categories, setCategories] = useState([]);
useEffect(() => {
// Fetch tags when component mounts
const fetchTags = async () => {
try {
const tags = await getTags(); // Fetch tags from API
const formattedTags = tags.data.map((tag) => ({
value: tag,
label: tag,
})); // Format tags for categories
setCategories(formattedTags); // Update state
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
code Copy code
fetchTags(); // Call the fetch function
}, []);
useEffect(() => {
async function fetchCampaigns() {
try {
const response = await getCampaigns();
const data = response.data;
code Copy code
if (Array.isArray(data)) {
setCampaigns(data);
setFilteredCampaigns(data); // Initialize filtered campaigns
} else {
console.error("Expected array but received:", data);
setError("Invalid data format");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCampaigns();
}, []);
useEffect(() => {
let updatedCampaigns = [...campaigns];
Show full message · 268 lines Assistant2024-10-04 14:39 UTC Copy response
To ensure all the search and sort fields have the same styling, you can define a common style object and apply it to each of the input and select components. Here's how you can adjust your code:
Define a style object to avoid repetition.
Apply this style object to the search input and both select components.
Here's the updated code:
Show full message · 285 lines Assistant2024-10-04 14:40 UTC Copy response
If you're referring to the ability in the dropdown to search and filter options like you mentioned before, such as adding a searchable feature to the dropdown, we can use the react-select library for this functionality. Here's how you can incorporate react-select specifically for making the tag dropdown searchable:
First, ensure you have react-select installed:
bash Copy code
npm install react-select
Then, update your component to use react-select for the tag selection dropdown. Here's the updated code demonstrating this change:
Show full message · 306 lines nah this is messed up, make it proper
Assistant2024-10-04 14:41 UTC Copy response
Alright, let's address this properly. I'll help you integrate react-select for the tag dropdown while ensuring it blends seamlessly with your component's existing styles.
Step-by-Step Integration:
Install react-select : If you haven't done it yet, make sure you have the package installed.
bash Copy code
npm install react-select
Update the CampaignsPage component to use react-select for the tag filtering.
Here's how the updated CampaignsPage component will look:
Show full message · 303 lines i cant see the typed things, and also the size of the tags search is different than others
Assistant2024-10-04 14:43 UTC Copy response
To address the visibility issues of typed text in the react-select component and to ensure consistent sizing of the dropdown with other input fields, you'll need to adjust the styles a bit more carefully.
Here's how you can adjust both the visibility of the text and ensure the component sizes consistently with the others:
Ensure Text Visibility : Set the color for the input text when typing to ensure it contrasts well with the background.
Consistent Component Size : Set a consistent width and height for the react-select component to match the other inputs.
Here's the revised component with these improvements:
Show full message · 320 lines it works but the tag search field is out of alignment and not same styles as others
Assistant2024-10-04 14:46 UTC Copy response
To ensure that the react-select dropdown matches the styling and alignment of the other form elements, you'll need to adjust both its CSS and its container. Here's how you can achieve consistent styling and alignment:
Consistent CSS Styles : Apply the same visual styles (background color, text color) directly to both the react-select component and the regular input/select elements.
Alignment : Use Flexbox or similar CSS utilities to ensure that all elements are aligned properly within their container.
Here's how you can update the component:
Show full message · 332 lines Not yet included in a published release.
// Filter by currentStatus
updatedCampaigns = updatedCampaigns.filter(
(campaign) => campaign.currentStatus === "active"
);
// Filter by search term
if (search) {
updatedCampaigns = updatedCampaigns.filter(
(campaign) =>
campaign.title.toLowerCase().includes(search.toLowerCase()) ||
campaign.description.toLowerCase().includes(search.toLowerCase())
);
}
// Filter by selected tag
if (selectedTag !== "all") {
updatedCampaigns = updatedCampaigns.filter((campaign) =>
campaign.tags.includes(selectedTag)
);
}
// Sort campaigns
switch (sortOption) {
case "goalAmount":
updatedCampaigns.sort((a, b) => b.goalAmount - a.goalAmount);
break;
case "goalAmountPercentage":
updatedCampaigns.sort((a, b) => {
const aPercentage = (a.totalFundsRaised / a.goalAmount) * 100;
const bPercentage = (b.totalFundsRaised / b.goalAmount) * 100;
return bPercentage - aPercentage;
});
break;
case "participants":
updatedCampaigns.sort(
(a, b) => b.participants.length - a.participants.length
);
break;
default:
break;
}
setFilteredCampaigns(updatedCampaigns);
}, [search, selectedTag, sortOption, campaigns]);
// Pagination logic
const indexOfLastCampaign = currentPage * itemsPerPage;
const indexOfFirstCampaign = indexOfLastCampaign - itemsPerPage;
const currentCampaigns = filteredCampaigns.slice(
indexOfFirstCampaign,
indexOfLastCampaign
);
// Calculate total pages
const totalPages = Math.ceil(filteredCampaigns.length / itemsPerPage);
code Copy code
<section className="pb-5 mt-5 mb-5">
<div className="container">
{/* Filters and Sorting */}
<div className="row mb-4">
<div className="col-md-4">
<input
type="text"
className="form-control"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
placeholder="Search by title or description"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="col-md-4">
<select
className="form-select"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
value={selectedTag}
onChange={(e) => setSelectedTag(e.target.value)}
>
<option value="all">All</option>
{categories.map((tag) => (
<option key={tag.value} value={tag.value}>
{tag.label}
</option>
))}
</select>
</div>
<div className="col-md-4">
<select
className="form-select"
value={sortOption}
style={{ backgroundColor: "#333333", color: "#ffffff" }}
onChange={(e) => setSortOption(e.target.value)}
>
<option value="none">Sort By</option>
<option value="goalAmount">Goal Amount</option>
<option value="goalAmountPercentage">
Goal Amount Percentage
</option>
<option value="participants">Number of Participants</option>
</select>
</div>
</div>
{/* Campaign Cards */}
<div className="row justify-content-center gy-4">
{loading && <p>Loading campaigns...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && currentCampaigns.length > 0 ? (
currentCampaigns.map((campaign) => (
<div className="col-xxl-3 col-lg-4 col-md-6" key={campaign._id}>
<FundraiseCard
id={campaign._id}
image={campaign.image}
title={campaign.title}
category={campaign.tags}
startAt={campaign.createdAt}
endAt={campaign.expiryDate}
creator={campaign.creator.username}
goalAmount={campaign.goalAmount}
remainingSlots={campaign.remainingSlots}
totalFundsRaised={campaign.totalFundsRaised}
description={campaign.description}
contributionPerSlot={campaign.contributionPerParticipant}
currentStatus={campaign.currentStatus}
/>
</div>
))
) : (
<div className="col-12 text-center">
<p className="glass-bg p-3 mb-0 text-center">
There're no campaigns at the moment
</p>
</div>
)}
</div>
{/* Pagination Controls */}
<div className="row mt-4">
<div className="col-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination justify-content-center">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage - 1)}
aria-label="Previous"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
<span aria-hidden="true">«</span>
</button>
</li>
{[...Array(totalPages).keys()].map((number) => (
<li
key={number}
className={`page-item ${
currentPage === number + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(number + 1)}
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
{number + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage + 1)}
aria-label="Next"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
</section>
</>
export default CampaignsPage;
here's the full page code, now make sure all the search/sort fields have same styling
import React, { useState, useEffect } from "react";
import PageBanner from "../../components/general/PageBanner";
import { getCampaigns, getTags } from "../../api";
import FundraiseCard from "../../components/general/FundraiseCard";
function CampaignsPage() {
const [campaigns, setCampaigns] = useState([]);
const [filteredCampaigns, setFilteredCampaigns] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 8; // Adjust items per page as needed
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const [selectedTag, setSelectedTag] = useState("all");
const [sortOption, setSortOption] = useState("none");
const [categories, setCategories] = useState([]);
const commonStyle = {
backgroundColor: "#333333",
color: "#ffffff",
};
useEffect(() => {
// Fetch tags when component mounts
const fetchTags = async () => {
try {
const tags = await getTags(); // Fetch tags from API
const formattedTags = tags.data.map((tag) => ({
value: tag,
label: tag,
})); // Format tags for categories
setCategories(formattedTags); // Update state
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
fetchTags(); // Call the fetch function
}, []);
useEffect(() => {
async function fetchCampaigns() {
try {
const response = await getCampaigns();
const data = response.data;
if (Array.isArray(data)) {
setCampaigns(data);
setFilteredCampaigns(data); // Initialize filtered campaigns
} else {
console.error("Expected array but received:", data);
setError("Invalid data format");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCampaigns();
}, []);
useEffect(() => {
let updatedCampaigns = [...campaigns];
// Filter by currentStatus
updatedCampaigns = updatedCampaigns.filter(
(campaign) => campaign.currentStatus === "active"
);
// Filter by search term
if (search) {
updatedCampaigns = updatedCampaigns.filter(
(campaign) =>
campaign.title.toLowerCase().includes(search.toLowerCase()) ||
campaign.description.toLowerCase().includes(search.toLowerCase())
);
}
// Filter by selected tag
if (selectedTag !== "all") {
updatedCampaigns = updatedCampaigns.filter((campaign) =>
campaign.tags.includes(selectedTag)
);
}
// Sort campaigns
switch (sortOption) {
case "goalAmount":
updatedCampaigns.sort((a, b) => b.goalAmount - a.goalAmount);
break;
case "goalAmountPercentage":
updatedCampaigns.sort((a, b) => {
const aPercentage = (a.totalFundsRaised / a.goalAmount) * 100;
const bPercentage = (b.totalFundsRaised / b.goalAmount) * 100;
return bPercentage - aPercentage;
});
break;
case "participants":
updatedCampaigns.sort(
(a, b) => b.participants.length - a.participants.length
);
break;
default:
break;
}
setFilteredCampaigns(updatedCampaigns);
}, [search, selectedTag, sortOption, campaigns]);
// Pagination logic
const indexOfLastCampaign = currentPage * itemsPerPage;
const indexOfFirstCampaign = indexOfLastCampaign - itemsPerPage;
const currentCampaigns = filteredCampaigns.slice(
indexOfFirstCampaign,
indexOfLastCampaign
);
// Calculate total pages
const totalPages = Math.ceil(filteredCampaigns.length / itemsPerPage);
return (
<>
<PageBanner
heading="All Campaigns"
text="Browse through various fundraising campaigns"
/>
<section className="pb-5 mt-5 mb-5">
<div className="container">
{/* Filters and Sorting */}
<div className="row mb-4">
<div className="col-md-4">
<input
type="text"
className="form-control"
style={commonStyle}
placeholder="Search by title or description"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="col-md-4">
<select
className="form-select"
style={commonStyle}
value={selectedTag}
onChange={(e) => setSelectedTag(e.target.value)}
>
<option value="all">All</option>
{categories.map((tag) => (
<option key={tag.value} value={tag.value}>
{tag.label}
</option>
))}
</select>
</div>
<div className="col-md-4">
<select
className="form-select"
style={commonStyle}
value={sortOption}
onChange={(e) => setSortOption(e.target.value)}
>
<option value="none">Sort By</option>
<option value="goalAmount">Goal Amount</option>
<option value="goalAmountPercentage">
Goal Amount Percentage
</option>
<option value="participants">Number of Participants</option>
</select>
</div>
</div>
{/* Campaign Cards */}
<div className="row justify-content-center gy-4">
{loading && <p>Loading campaigns...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && currentCampaigns.length > 0 ? (
currentCampaigns.map((campaign) => (
<div className="col-xxl-3 col-lg-4 col-md-6" key={campaign._id}>
<FundraiseCard
id={campaign._id}
image={campaign.image}
title={campaign.title}
category={campaign.tags}
startAt={campaign.createdAt}
endAt={campaign.expiryDate}
creator={campaign.creator.username}
goalAmount={campaign.goalAmount}
remainingSlots={campaign.remainingSlots}
totalFundsRaised={campaign.totalFundsRaised}
description={campaign.description}
contributionPerSlot={campaign.contributionPerParticipant}
currentStatus={campaign.currentStatus}
/>
</div>
))
) : (
<div className="col-12 text-center">
<p className="glass-bg p-3 mb-0 text-center">
There're no campaigns at the moment
</p>
</div>
)}
</div>
{/* Pagination Controls */}
<div className="row mt-4">
<div className="col-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination justify-content-center">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage - 1)}
aria-label="Previous"
style={commonStyle}
>
<span aria-hidden="true">«</span>
</button>
</li>
{[...Array(totalPages).keys()].map((number) => (
<li
key={number}
className={`page-item ${
currentPage === number + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(number + 1)}
style={commonStyle}
>
{number + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage + 1)}
aria-label="Next"
style={commonStyle}
>
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
</section>
</>
);
}
export default CampaignsPage;
Changes Made:
Introduced commonStyle to contain the shared CSS styles.
Applied commonStyle to the search input and both select components to ensure they have consistent styling.
Also applied commonStyle to the pagination buttons to maintain a unified look across the component.
This will ensure all interactive elements share the same background and font colors for a cohesive design.
import React, { useState, useEffect } from "react";
import Select from "react-select"; // Import from react-select
import PageBanner from "../../components/general/PageBanner";
import { getCampaigns, getTags } from "../../api";
import FundraiseCard from "../../components/general/FundraiseCard";
function CampaignsPage() {
const [campaigns, setCampaigns] = useState([]);
const [filteredCampaigns, setFilteredCampaigns] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 8; // Adjust items per page as needed
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const [selectedTag, setSelectedTag] = useState("all");
const [sortOption, setSortOption] = useState("none");
const [categories, setCategories] = useState([]);
const commonStyle = {
backgroundColor: "#333333",
color: "#ffffff",
};
useEffect(() => {
// Fetch tags when component mounts
const fetchTags = async () => {
try {
const tags = await getTags(); // Fetch tags from API
const formattedTags = tags.data.map((tag) => ({
value: tag,
label: tag,
})); // Format tags for categories
setCategories([{ value: "all", label: "All" }, ...formattedTags]); // Include "All" option
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
fetchTags(); // Call the fetch function
}, []);
useEffect(() => {
async function fetchCampaigns() {
try {
const response = await getCampaigns();
const data = response.data;
if (Array.isArray(data)) {
setCampaigns(data);
setFilteredCampaigns(data); // Initialize filtered campaigns
} else {
console.error("Expected array but received:", data);
setError("Invalid data format");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCampaigns();
}, []);
useEffect(() => {
let updatedCampaigns = [...campaigns];
// Filter by currentStatus
updatedCampaigns = updatedCampaigns.filter(
(campaign) => campaign.currentStatus === "active"
);
// Filter by search term
if (search) {
updatedCampaigns = updatedCampaigns.filter(
(campaign) =>
campaign.title.toLowerCase().includes(search.toLowerCase()) ||
campaign.description.toLowerCase().includes(search.toLowerCase())
);
}
// Filter by selected tag
if (selectedTag !== "all") {
updatedCampaigns = updatedCampaigns.filter((campaign) =>
campaign.tags.includes(selectedTag)
);
}
// Sort campaigns
switch (sortOption) {
case "goalAmount":
updatedCampaigns.sort((a, b) => b.goalAmount - a.goalAmount);
break;
case "goalAmountPercentage":
updatedCampaigns.sort((a, b) => {
const aPercentage = (a.totalFundsRaised / a.goalAmount) * 100;
const bPercentage = (b.totalFundsRaised / b.goalAmount) * 100;
return bPercentage - aPercentage;
});
break;
case "participants":
updatedCampaigns.sort(
(a, b) => b.participants.length - a.participants.length
);
break;
default:
break;
}
setFilteredCampaigns(updatedCampaigns);
}, [search, selectedTag, sortOption, campaigns]);
// Pagination logic
const indexOfLastCampaign = currentPage * itemsPerPage;
const indexOfFirstCampaign = indexOfLastCampaign - itemsPerPage;
const currentCampaigns = filteredCampaigns.slice(
indexOfFirstCampaign,
indexOfLastCampaign
);
// Calculate total pages
const totalPages = Math.ceil(filteredCampaigns.length / itemsPerPage);
return (
<>
<PageBanner
heading="All Campaigns"
text="Browse through various fundraising campaigns"
/>
<section className="pb-5 mt-5 mb-5">
<div className="container">
{/* Filters and Sorting */}
<div className="row mb-4">
<div className="col-md-4">
<input
type="text"
className="form-control"
style={commonStyle}
placeholder="Search by title or description"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="col-md-4">
<Select
className="form-select"
styles={{
control: (base) => ({
...base,
backgroundColor: commonStyle.backgroundColor,
color: commonStyle.color,
}),
singleValue: (base) => ({
...base,
color: commonStyle.color,
}),
menu: (base) => ({
...base,
backgroundColor: commonStyle.backgroundColor,
}),
option: (base, state) => ({
...base,
backgroundColor: state.isSelected ? "#666666" : commonStyle.backgroundColor,
color: commonStyle.color,
'&:hover': {
backgroundColor: "#555555",
},
}),
}}
value={categories.find(option => option.value === selectedTag)}
onChange={(option) => setSelectedTag(option.value)}
options={categories}
isSearchable={true}
/>
</div>
<div className="col-md-4">
<select
className="form-select"
style={commonStyle}
value={sortOption}
onChange={(e) => setSortOption(e.target.value)}
>
<option value="none">Sort By</option>
<option value="goalAmount">Goal Amount</option>
<option value="goalAmountPercentage">
Goal Amount Percentage
</option>
<option value="participants">Number of Participants</option>
</select>
</div>
</div>
{/* Campaign Cards */}
<div className="row justify-content-center gy-4">
{loading && <p>Loading campaigns...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && currentCampaigns.length > 0 ? (
currentCampaigns.map((campaign) => (
<div className="col-xxl-3 col-lg-4 col-md-6" key={campaign._id}>
<FundraiseCard
id={campaign._id}
image={campaign.image}
title={campaign.title}
category={campaign.tags}
startAt={campaign.createdAt}
endAt={campaign.expiryDate}
creator={campaign.creator.username}
goalAmount={campaign.goalAmount}
remainingSlots={campaign.remainingSlots}
totalFundsRaised={campaign.totalFundsRaised}
description={campaign.description}
contributionPerSlot={campaign.contributionPerParticipant}
currentStatus={campaign.currentStatus}
/>
</div>
))
) : (
<div className="col-12 text-center">
<p className="glass-bg p-3 mb-0 text-center">
There're no campaigns at the moment
</p>
</div>
)}
</div>
{/* Pagination Controls */}
<div className="row mt-4">
<div className="col-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination justify-content-center">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage - 1)}
aria-label="Previous"
style={commonStyle}
>
<span aria-hidden="true">«</span>
</button>
</li>
{[...Array(totalPages).keys()].map((number) => (
<li
key={number}
className={`page-item ${
currentPage === number + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(number + 1)}
style={commonStyle}
>
{number + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage + 1)}
aria-label="Next"
style={commonStyle}
>
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
</section>
</>
);
}
export default CampaignsPage;
Key Changes:
Replaced the tag select with Select from react-select.
Set up the style for react-select to match the common style using the styles prop.
Used isSearchable={true} to make the dropdown searchable.
Now, with the react-select component, your tag dropdown will be searchable, enhancing the functionality and user experience.
import React, { useState, useEffect } from "react";
import Select from "react-select"; // Import react-select
import PageBanner from "../../components/general/PageBanner";
import { getCampaigns, getTags } from "../../api";
import FundraiseCard from "../../components/general/FundraiseCard";
function CampaignsPage() {
const [campaigns, setCampaigns] = useState([]);
const [filteredCampaigns, setFilteredCampaigns] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 8;
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const [selectedTag, setSelectedTag] = useState({ value: "all", label: "All" });
const [sortOption, setSortOption] = useState("none");
const [categories, setCategories] = useState([]);
const commonStyle = {
control: (base) => ({
...base,
backgroundColor: "#333333",
color: "#ffffff",
borderColor: "#555555",
'&:hover': { borderColor: "#777777" }, // Hover style
}),
singleValue: (base) => ({
...base,
color: "#ffffff",
}),
menu: (base) => ({
...base,
backgroundColor: "#333333",
}),
option: (base, state) => ({
...base,
backgroundColor: state.isSelected ? "#666666" : "#333333",
color: "#ffffff",
'&:hover': {
backgroundColor: "#555555",
},
}),
};
useEffect(() => {
const fetchTags = async () => {
try {
const tags = await getTags();
const formattedTags = tags.data.map((tag) => ({
value: tag,
label: tag,
}));
setCategories([{ value: "all", label: "All" }, ...formattedTags]);
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
fetchTags();
}, []);
useEffect(() => {
async function fetchCampaigns() {
try {
const response = await getCampaigns();
const data = response.data;
if (Array.isArray(data)) {
setCampaigns(data);
setFilteredCampaigns(data);
} else {
console.error("Expected array but received:", data);
setError("Invalid data format");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCampaigns();
}, []);
useEffect(() => {
let updatedCampaigns = [...campaigns];
// Filter by currentStatus
updatedCampaigns = updatedCampaigns.filter(
(campaign) => campaign.currentStatus === "active"
);
// Filter by search term
if (search) {
updatedCampaigns = updatedCampaigns.filter(
(campaign) =>
campaign.title.toLowerCase().includes(search.toLowerCase()) ||
campaign.description.toLowerCase().includes(search.toLowerCase())
);
}
// Filter by selected tag
if (selectedTag.value !== "all") {
updatedCampaigns = updatedCampaigns.filter((campaign) =>
campaign.tags.includes(selectedTag.value)
);
}
// Sort campaigns
switch (sortOption) {
case "goalAmount":
updatedCampaigns.sort((a, b) => b.goalAmount - a.goalAmount);
break;
case "goalAmountPercentage":
updatedCampaigns.sort((a, b) => {
const aPercentage = (a.totalFundsRaised / a.goalAmount) * 100;
const bPercentage = (b.totalFundsRaised / b.goalAmount) * 100;
return bPercentage - aPercentage;
});
break;
case "participants":
updatedCampaigns.sort(
(a, b) => b.participants.length - a.participants.length
);
break;
default:
break;
}
setFilteredCampaigns(updatedCampaigns);
}, [search, selectedTag, sortOption, campaigns]);
const indexOfLastCampaign = currentPage * itemsPerPage;
const indexOfFirstCampaign = indexOfLastCampaign - itemsPerPage;
const currentCampaigns = filteredCampaigns.slice(
indexOfFirstCampaign,
indexOfLastCampaign
);
const totalPages = Math.ceil(filteredCampaigns.length / itemsPerPage);
return (
<>
<PageBanner
heading="All Campaigns"
text="Browse through various fundraising campaigns"
/>
<section className="pb-5 mt-5 mb-5">
<div className="container">
<div className="row mb-4">
<div className="col-md-4">
<input
type="text"
className="form-control"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
placeholder="Search by title or description"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="col-md-4">
<Select
styles={commonStyle}
value={selectedTag}
onChange={(option) => setSelectedTag(option)}
options={categories}
isSearchable={true}
/>
</div>
<div className="col-md-4">
<select
className="form-select"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
value={sortOption}
onChange={(e) => setSortOption(e.target.value)}
>
<option value="none">Sort By</option>
<option value="goalAmount">Goal Amount</option>
<option value="goalAmountPercentage">
Goal Amount Percentage
</option>
<option value="participants">Number of Participants</option>
</select>
</div>
</div>
<div className="row justify-content-center gy-4">
{loading && <p>Loading campaigns...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && currentCampaigns.length > 0 ? (
currentCampaigns.map((campaign) => (
<div className="col-xxl-3 col-lg-4 col-md-6" key={campaign._id}>
<FundraiseCard
id={campaign._id}
image={campaign.image}
title={campaign.title}
category={campaign.tags}
startAt={campaign.createdAt}
endAt={campaign.expiryDate}
creator={campaign.creator.username}
goalAmount={campaign.goalAmount}
remainingSlots={campaign.remainingSlots}
totalFundsRaised={campaign.totalFundsRaised}
description={campaign.description}
contributionPerSlot={campaign.contributionPerParticipant}
currentStatus={campaign.currentStatus}
/>
</div>
))
) : (
<div className="col-12 text-center">
<p className="glass-bg p-3 mb-0 text-center">
There're no campaigns at the moment
</p>
</div>
)}
</div>
<div className="row mt-4">
<div className="col-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination justify-content-center">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage - 1)}
aria-label="Previous"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
<span aria-hidden="true">«</span>
</button>
</li>
{[...Array(totalPages).keys()].map((number) => (
<li
key={number}
className={`page-item ${
currentPage === number + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(number + 1)}
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
{number + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage + 1)}
aria-label="Next"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
</section>
</>
);
}
export default CampaignsPage;
Key Points:
react-select Integration : This allows you to incorporate search functionality within the tag selection dropdown, providing a more flexible user interface for filtering campaigns by tag.
Unified Styling : The CSS styling for react-select is aligned with your existing input and select styles to ensure a consistent look and feel.
State Management : Note that selectedTag is now an object { value, label }, so change the filtering logic to use selectedTag.value instead.
Option Inclusion : The options array now includes an "All" option to allow users to view all campaigns.
This setup ensures that your dropdown is both searchable and visually consistent with the rest of the input fields.
import React, { useState, useEffect } from "react";
import Select from "react-select"; // Import react-select
import PageBanner from "../../components/general/PageBanner";
import { getCampaigns, getTags } from "../../api";
import FundraiseCard from "../../components/general/FundraiseCard";
function CampaignsPage() {
const [campaigns, setCampaigns] = useState([]);
const [filteredCampaigns, setFilteredCampaigns] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 8;
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const [selectedTag, setSelectedTag] = useState({ value: "all", label: "All" });
const [sortOption, setSortOption] = useState("none");
const [categories, setCategories] = useState([]);
const commonStyle = {
width: "100%", // Ensure full width
minHeight: "38px", // Ensuring the size matches other components
control: (base) => ({
...base,
backgroundColor: "#333333",
color: "#ffffff",
borderColor: "#555555",
minHeight: "38px", // Match height of input and select
'&:hover': { borderColor: "#777777" }, // Hover style
}),
valueContainer: (base) => ({
...base,
color: "#ffffff",
}),
input: (base) => ({
...base,
color: "white", // Ensures the typed text is visible
}),
singleValue: (base) => ({
...base,
color: "#ffffff",
}),
menu: (base) => ({
...base,
backgroundColor: "#333333",
}),
option: (base, state) => ({
...base,
backgroundColor: state.isSelected ? "#666666" : "#333333",
color: "#ffffff",
'&:hover': {
backgroundColor: "#555555",
},
}),
};
useEffect(() => {
const fetchTags = async () => {
try {
const tags = await getTags();
const formattedTags = tags.data.map((tag) => ({
value: tag,
label: tag,
}));
setCategories([{ value: "all", label: "All" }, ...formattedTags]);
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
fetchTags();
}, []);
useEffect(() => {
async function fetchCampaigns() {
try {
const response = await getCampaigns();
const data = response.data;
if (Array.isArray(data)) {
setCampaigns(data);
setFilteredCampaigns(data);
} else {
console.error("Expected array but received:", data);
setError("Invalid data format");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCampaigns();
}, []);
useEffect(() => {
let updatedCampaigns = [...campaigns];
// Filter by currentStatus
updatedCampaigns = updatedCampaigns.filter(
(campaign) => campaign.currentStatus === "active"
);
// Filter by search term
if (search) {
updatedCampaigns = updatedCampaigns.filter(
(campaign) =>
campaign.title.toLowerCase().includes(search.toLowerCase()) ||
campaign.description.toLowerCase().includes(search.toLowerCase())
);
}
// Filter by selected tag
if (selectedTag.value !== "all") {
updatedCampaigns = updatedCampaigns.filter((campaign) =>
campaign.tags.includes(selectedTag.value)
);
}
// Sort campaigns
switch (sortOption) {
case "goalAmount":
updatedCampaigns.sort((a, b) => b.goalAmount - a.goalAmount);
break;
case "goalAmountPercentage":
updatedCampaigns.sort((a, b) => {
const aPercentage = (a.totalFundsRaised / a.goalAmount) * 100;
const bPercentage = (b.totalFundsRaised / b.goalAmount) * 100;
return bPercentage - aPercentage;
});
break;
case "participants":
updatedCampaigns.sort(
(a, b) => b.participants.length - a.participants.length
);
break;
default:
break;
}
setFilteredCampaigns(updatedCampaigns);
}, [search, selectedTag, sortOption, campaigns]);
const indexOfLastCampaign = currentPage * itemsPerPage;
const indexOfFirstCampaign = indexOfLastCampaign - itemsPerPage;
const currentCampaigns = filteredCampaigns.slice(
indexOfFirstCampaign,
indexOfLastCampaign
);
const totalPages = Math.ceil(filteredCampaigns.length / itemsPerPage);
return (
<>
<PageBanner
heading="All Campaigns"
text="Browse through various fundraising campaigns"
/>
<section className="pb-5 mt-5 mb-5">
<div className="container">
<div className="row mb-4">
<div className="col-md-4">
<input
type="text"
className="form-control"
style={{ backgroundColor: "#333333", color: "#ffffff", minHeight: "38px" }}
placeholder="Search by title or description"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="col-md-4">
<Select
styles={commonStyle}
value={selectedTag}
onChange={(option) => setSelectedTag(option)}
options={categories}
isSearchable={true}
theme={(theme) => ({
...theme,
borderRadius: 0,
colors: {
...theme.colors,
primary25: '#555555',
primary: '#888888',
},
})}
/>
</div>
<div className="col-md-4">
<select
className="form-select"
style={{ backgroundColor: "#333333", color: "#ffffff", minHeight: "38px" }}
value={sortOption}
onChange={(e) => setSortOption(e.target.value)}
>
<option value="none">Sort By</option>
<option value="goalAmount">Goal Amount</option>
<option value="goalAmountPercentage">
Goal Amount Percentage
</option>
<option value="participants">Number of Participants</option>
</select>
</div>
</div>
<div className="row justify-content-center gy-4">
{loading && <p>Loading campaigns...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && currentCampaigns.length > 0 ? (
currentCampaigns.map((campaign) => (
<div className="col-xxl-3 col-lg-4 col-md-6" key={campaign._id}>
<FundraiseCard
id={campaign._id}
image={campaign.image}
title={campaign.title}
category={campaign.tags}
startAt={campaign.createdAt}
endAt={campaign.expiryDate}
creator={campaign.creator.username}
goalAmount={campaign.goalAmount}
remainingSlots={campaign.remainingSlots}
totalFundsRaised={campaign.totalFundsRaised}
description={campaign.description}
contributionPerSlot={campaign.contributionPerParticipant}
currentStatus={campaign.currentStatus}
/>
</div>
))
) : (
<div className="col-12 text-center">
<p className="glass-bg p-3 mb-0 text-center">
There're no campaigns at the moment
</p>
</div>
)}
</div>
<div className="row mt-4">
<div className="col-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination justify-content-center">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage - 1)}
aria-label="Previous"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
<span aria-hidden="true">«</span>
</button>
</li>
{[...Array(totalPages).keys()].map((number) => (
<li
key={number}
className={`page-item ${
currentPage === number + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(number + 1)}
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
{number + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage + 1)}
aria-label="Next"
style={{ backgroundColor: "#333333", color: "#ffffff" }}
>
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
</section>
</>
);
}
export default CampaignsPage;
Changes Made:
Styling Consistency : The minHeight property is explicitly set for the react-select control to match the native input elements.
Typed Text Visibility : The input style inside react-select is adjusted to ensure that any typed text is clearly visible.
Width Adjustment : width: "100%" is set to keep the react-select component's width consistent with other elements, allowing it to adapt to the column size.
By making these adjustments, the react-select component should visually integrate seamlessly with the rest of your form elements.
import React, { useState, useEffect } from "react";
import Select from "react-select";
import PageBanner from "../../components/general/PageBanner";
import { getCampaigns, getTags } from "../../api";
import FundraiseCard from "../../components/general/FundraiseCard";
function CampaignsPage() {
const [campaigns, setCampaigns] = useState([]);
const [filteredCampaigns, setFilteredCampaigns] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 8;
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [search, setSearch] = useState("");
const [selectedTag, setSelectedTag] = useState({
value: "all",
label: "All",
});
const [sortOption, setSortOption] = useState("none");
const [categories, setCategories] = useState([]);
const commonStyle = {
minHeight: "38px",
backgroundColor: "#333333",
borderColor: "#555555",
color: "#ffffff",
};
const reactSelectStyles = {
control: (base) => ({
...base,
backgroundColor: commonStyle.backgroundColor,
borderColor: commonStyle.borderColor,
minHeight: commonStyle.minHeight,
display: "flex",
"align-items": "center",
color: commonStyle.color,
}),
valueContainer: (base) => ({
...base,
padding: "0 8px",
}),
input: (base) => ({
...base,
color: commonStyle.color,
}),
singleValue: (base) => ({
...base,
color: commonStyle.color,
}),
menu: (base) => ({
...base,
backgroundColor: commonStyle.backgroundColor,
}),
option: (base, state) => ({
...base,
backgroundColor: state.isSelected ? "#666666" : commonStyle.backgroundColor,
color: commonStyle.color,
'&:hover': {
backgroundColor: "#555555",
},
}),
};
useEffect(() => {
const fetchTags = async () => {
try {
const tags = await getTags();
const formattedTags = tags.data.map((tag) => ({
value: tag,
label: tag,
}));
setCategories([{ value: "all", label: "All" }, ...formattedTags]);
} catch (error) {
console.error("Failed to fetch tags:", error);
}
};
fetchTags();
}, []);
useEffect(() => {
async function fetchCampaigns() {
try {
const response = await getCampaigns();
const data = response.data;
if (Array.isArray(data)) {
setCampaigns(data);
setFilteredCampaigns(data);
} else {
console.error("Expected array but received:", data);
setError("Invalid data format");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchCampaigns();
}, []);
useEffect(() => {
let updatedCampaigns = [...campaigns];
updatedCampaigns = updatedCampaigns.filter(
(campaign) => campaign.currentStatus === "active"
);
if (search) {
updatedCampaigns = updatedCampaigns.filter(
(campaign) =>
campaign.title.toLowerCase().includes(search.toLowerCase()) ||
campaign.description.toLowerCase().includes(search.toLowerCase())
);
}
if (selectedTag.value !== "all") {
updatedCampaigns = updatedCampaigns.filter((campaign) =>
campaign.tags.includes(selectedTag.value)
);
}
switch (sortOption) {
case "goalAmount":
updatedCampaigns.sort((a, b) => b.goalAmount - a.goalAmount);
break;
case "goalAmountPercentage":
updatedCampaigns.sort((a, b) => {
const aPercentage = (a.totalFundsRaised / a.goalAmount) * 100;
const bPercentage = (b.totalFundsRaised / b.goalAmount) * 100;
return bPercentage - aPercentage;
});
break;
case "participants":
updatedCampaigns.sort(
(a, b) => b.participants.length - a.participants.length
);
break;
default:
break;
}
setFilteredCampaigns(updatedCampaigns);
}, [search, selectedTag, sortOption, campaigns]);
const indexOfLastCampaign = currentPage * itemsPerPage;
const indexOfFirstCampaign = indexOfLastCampaign - itemsPerPage;
const currentCampaigns = filteredCampaigns.slice(
indexOfFirstCampaign,
indexOfLastCampaign
);
const totalPages = Math.ceil(filteredCampaigns.length / itemsPerPage);
return (
<>
<PageBanner
heading="All Campaigns"
text="Browse through various fundraising campaigns"
/>
<section className="pb-5 mt-5 mb-5">
<div className="container">
<div className="row mb-4 align-items-center">
<div className="col-md-4">
<input
type="text"
className="form-control"
style={commonStyle}
placeholder="Search by title or description"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="col-md-4">
<Select
styles={reactSelectStyles}
value={selectedTag}
onChange={(option) => setSelectedTag(option)}
options={categories}
isSearchable={true}
theme={(theme) => ({
...theme,
borderRadius: 0,
colors: {
...theme.colors,
primary25: '#555555',
primary: '#888888',
},
})}
/>
</div>
<div className="col-md-4">
<select
className="form-select"
style={commonStyle}
value={sortOption}
onChange={(e) => setSortOption(e.target.value)}
>
<option value="none">Sort By</option>
<option value="goalAmount">Goal Amount</option>
<option value="goalAmountPercentage">
Goal Amount Percentage
</option>
<option value="participants">Number of Participants</option>
</select>
</div>
</div>
<div className="row justify-content-center gy-4">
{loading && <p>Loading campaigns...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && currentCampaigns.length > 0 ? (
currentCampaigns.map((campaign) => (
<div className="col-xxl-3 col-lg-4 col-md-6" key={campaign._id}>
<FundraiseCard
id={campaign._id}
image={campaign.image}
title={campaign.title}
category={campaign.tags}
startAt={campaign.createdAt}
endAt={campaign.expiryDate}
creator={campaign.creator.username}
goalAmount={campaign.goalAmount}
remainingSlots={campaign.remainingSlots}
totalFundsRaised={campaign.totalFundsRaised}
description={campaign.description}
contributionPerSlot={campaign.contributionPerParticipant}
currentStatus={campaign.currentStatus}
/>
</div>
))
) : (
<div className="col-12 text-center">
<p className="glass-bg p-3 mb-0 text-center">
There're no campaigns at the moment
</p>
</div>
)}
</div>
<div className="row mt-4">
<div className="col-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination justify-content-center">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage - 1)}
aria-label="Previous"
style={{
backgroundColor: "#333333",
color: "#ffffff",
}}
>
<span aria-hidden="true">«</span>
</button>
</li>
{[...Array(totalPages).keys()].map((number) => (
<li
key={number}
className={`page-item ${
currentPage === number + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(number + 1)}
style={{
backgroundColor: "#333333",
color: "#ffffff",
}}
>
{number + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => setCurrentPage(currentPage + 1)}
aria-label="Next"
style={{
backgroundColor: "#333333",
color: "#ffffff",
}}
>
<span aria-hidden="true">»</span>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>
</section>
</>
);
}
export default CampaignsPage;
Adjustments Made:
CSS Alignment : The react-select component style is adjusted to use Flexbox alignment, mimicking the native input styling.
Visual Consistency : The commonStyle object now applies a consistent look across all components, including hover behavior and minimum height.
Component Alignment : The use of align-items-center in the Bootstrapped row ensures that all controls are vertically centered.
These changes ensure that the react-select component matches the look and feel of the other input fields, aligning them properly both vertically and horizontally.