import React, { useState, useEffect } from "react"; import PageBanner from…
- User
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); } };
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 ( <>
<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;
make the whole code use Select from react-select and add search functionality to the tags
- Assistant
To integrate
react-selectinto yourCampaignsPage, we need to replace the native<select>elements withSelectcomponents fromreact-select. We'll also add the capability to search for tags usingreact-select's built-in filter capabilities. Below is how you can modify your code to achieve this:First, make sure that
react-selectis installed in your project. If it’s not already installed, you can add it using npm or yarn:npm install react-selector
yarn add react-selectNow, update the
CampaignsPagecomponent to utilizereact-select: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([]); 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"> <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 options={categories} value={selectedTag} onChange={setSelectedTag} styles={{ control: (base) => ({ ...base, backgroundColor: "#333333", color: "#ffffff", }), menu: (base) => ({ ...base, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: state.isSelected ? "#ffffff" : "#000000", backgroundColor: state.isSelected ? "#555555" : "#333333", "&:hover": { backgroundColor: "#444444", color: "#ffffff", }, }), }} isClearable={true} placeholder="Select Tag" /> </div> <div className="col-md-4"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={{ value: sortOption, label: sortOption }} onChange={(option) => setSortOption(option.value)} styles={{ control: (base) => ({ ...base, backgroundColor: "#333333", color: "#ffffff", }), menu: (base) => ({ ...base, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: state.isSelected ? "#ffffff" : "#000000", backgroundColor: state.isSelected ? "#555555" : "#333333", "&:hover": { backgroundColor: "#444444", color: "#ffffff", }, }), }} isClearable={false} placeholder="Sort By" /> </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;Key Modifications:
-
Import
react-select: We begin by importingSelectfromreact-select. -
Replace Native Selects with React-Select:
- We use
Selectfor both tags and sort options. - Tags are now selectable using the
Selectcomponent with search functionality, making it easier to find specific tags.
- We use
-
React-Select Styles:
- Modify the styles of the
Selectcomponent to blend with your application's aesthetic, adjusting colors and background.
- Modify the styles of the
-
Handling State with React-Select:
- The
Selectcomponent'sonChangeprop passes the entire selected option, so we need to handle it accordingly. For example,setSelectedTag(option)instead ofe.target.value.
- The
This setup will allow users to effectively search and select tags as well as sort options for the campaigns.
-
- User
the stylings are off
- Assistant
To address styling issues with
react-select, we can adjust thestylesprop to fine-tune the appearance of the dropdown to align better with your application's theme. Thestylesprop accepts a collection of style functions, allowing you to override the default styles. Let’s refine them: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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: 'none', "&:hover": { borderColor: "#777777", } }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", } }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", } }), indicatorSeparator: (provided) => ({ ...provided, display: "none", }), }; 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({ value: "none", label: "Sort By" }); const [categories, setCategories] = useState([]); 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.value) { 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 options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={true} placeholder="Select Tag" /> </div> <div className="col-md-4"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Styling Details:
control: Adjusts the main control element's styling, including border color, background, and hover effects.menu: Modifies the dropdown menu's background color.singleValue: Targets the selected item's text color.option: Changes the style for each dropdown option, including hover effects for better interaction.placeholder: Handles the styling of the placeholder text.dropdownIndicator: Provides overrides for dropdown icons.
Fine-tuning the colors and styling can help create a seamless look and feel for your application. Adjust the values of colors according to your design requirements to ensure visibility and aesthetic cohesion.
- User
the tags thing search typed things dont show up
- Assistant
If you're experiencing issues where the search functionality on the tag selection isn't working properly, the issue might be related to how the tags are being filtered or displayed. By default,
react-selectshould have built-in search functionality, but there might be issues if the component is not set up correctly. Let's ensure that everything is set up properly:-
Ensure Options are Correctly Formatted: The options for
react-selectshould be an array of objects, each with avalueand alabel. -
Ensure React-Select Uses Default Filtering: By default,
react-selectshould allow searching based on thelabelfield. Make sure thelabelfield contains the desired text that should be searched. -
Verify that Filtering is not Disabled: Make sure that there are no props inadvertently disabling the filtering behavior.
Here’s the revised code snippet focusing on the
Selectcomponent for tags: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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: (provided) => ({ ...provided, display: "none", }), }; 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(null); const [sortOption, setSortOption] = useState(null); const [categories, setCategories] = useState([]); 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]; if (selectedTag && selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } switch (sortOption?.value) { 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 options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={true} placeholder="Select Tag" filterOption={(option, inputValue) => option.data.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-4"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Key Changes
- Added
filterOptionFunction: Provides custom filtering logic that ensures options containing the typed input are displayed. - Initial State Adjustments: Made sure initial states for
selectedTagandsortOptionuse full option objects instead of primitives.
Ensure
react-selectis Functioning Properly:- Make sure there are no additional props or logic conflicting with
react-select’s default behavior. - Confirm that the
optionsare being correctly rendered by logging them. - Confirm that
react-select’s version supports the expected features, or check for updates.
By ensuring that these details are correctly configured, the search functionality should work as expected, allowing users to filter tags.
-
- User
the typed letters dont appear is what i meant
- Assistant
If typed letters in the
react-selectinput field aren't appearing, it could be due to styling issues that make the text either invisible or hard to read. Let’s adjust the styles to make the input text clearly visible:-
Inspect Input Styles: We'll ensure that the input text color contrasts well against the background.
-
Debug Specific Sections: By checking individual style configurations, we can pinpoint where the input's styles are going awry.
Here’s how you can modify the
react-selectstyles to address this issue: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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: () => ({ display: "none", }), input: (provided) => ({ ...provided, color: "#ffffff", // Ensure the input text is visible }), }; 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(null); const [sortOption, setSortOption] = useState(null); const [categories, setCategories] = useState([]); 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]; if (selectedTag && selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } switch (sortOption?.value) { 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 options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={true} placeholder="Select Tag" filterOption={(option, inputValue) => option.data.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-4"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Explanation
input: We've added a style override for theinputpart ofreact-select. Thecoloris set to bright white (#ffffff), which contrasts well with a dark background.- Maintenance and Debugging: Ensure that no other CSS is overriding the styles we've set here. You can inspect the elements using browser developer tools to confirm the correct styles are applied.
This should make sure the text appears clearly when typed into the
react-selectcomponent. Adjust the color if your background is different to maintain appropriate contrast. -
- User
works well, now make the first search button also in the style as the both of them
- Assistant
Let's update the styles for the native
<input>search field so that it matches the styling of thereact-selectcomponents. We will make sure everything follows the same theme for consistency. This involves applying similar styling to the button, such as background color, text color, and hover effects.Here's how you can adjust the styles for the first search input field:
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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: () => ({ display: "none", }), input: (provided) => ({ ...provided, color: "#ffffff", }), }; const inputStyles = { backgroundColor: "#333333", color: "#ffffff", border: "1px solid #555555", outline: "none", boxShadow: "none", borderRadius: "4px", padding: "8px", width: "100%", "&:focus": { borderColor: "#777777", }, "&::placeholder": { color: "#bbbbbb", }, }; 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(null); const [sortOption, setSortOption] = useState(null); const [categories, setCategories] = useState([]); 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]; if (selectedTag && selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } switch (sortOption?.value) { 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={inputStyles} placeholder="Search by title or description" value={search} onChange={(e) => setSearch(e.target.value)} /> </div> <div className="col-md-4"> <Select options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={true} placeholder="Select Tag" filterOption={(option, inputValue) => option.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-4"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Key Style Adjustments
inputStyles: We've applied a consistent style to the native<input>element, matching it to thereact-selectcomponents.- Background Color and Border: Ensuring the text and background create sufficient contrast.
- Placeholder Color: Styled for contrast and readability.
- Hover and Focus Effects: Included to maintain visual consistency in interactive states.
By aligning the styles across the input and select components, we achieve a more cohesive design and consistent user experience across the application. Adjust the color values if your overall theme requires different shades.
- User
still styling looks off (size bad)
- Assistant
To adjust the size of the input and
react-selectcomponents so they align better in terms of height and width, you can ensure that the styling is consistent. We will focus on setting explicit height, padding, and ensuring width consistency. Here is how you can refine the styles:-
Set Consistent Height and Padding: Make sure both the input and select components use the same height and padding.
-
Adjust Font-Size and Other CSS Properties: Modify font-size, padding, and line-height to ensure they align well visually.
Here's an updated version:
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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, height: "38px", // Make sure this aligns with input height }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: () => ({ display: "none", }), input: (provided) => ({ ...provided, color: "#ffffff", }), }; const inputStyles = { backgroundColor: "#333333", color: "#ffffff", border: "1px solid #555555", outline: "none", boxShadow: "none", borderRadius: "4px", padding: "0 12px", // Same padding as select height: "38px", // Same height as select fontSize: "1rem", // Consistent with select width: "100%", "&:focus": { borderColor: "#777777", }, "&::placeholder": { color: "#bbbbbb", }, }; 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(null); const [sortOption, setSortOption] = useState(null); const [categories, setCategories] = useState([]); 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]; if (selectedTag && selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } switch (sortOption?.value) { 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={inputStyles} placeholder="Search by title or description" value={search} onChange={(e) => setSearch(e.target.value)} /> </div> <div className="col-md-4"> <Select options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={true} placeholder="Select Tag" filterOption={(option, inputValue) => option.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-4"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Key Adjustments
- Height and Padding: Applied consistent
heightandpaddingto bothinputandSelectcomponents. - Font Size: Ensured
fontSizeis set to1remfor a uniform look. - Width (100%): Both the input and
Selectcomponents take the full width of their container columns.
Adjusting these styles should create a more visually aligned interface for both input types, providing a cleaner aesthetic and consistent interaction model for your users. Feel free to tweak these values further to match the specific design needs of your application.
-
- User
good work. now make add one more filter which has All Active Inactive campaigns
- Assistant
To add another filter for selecting campaigns based on their status (All, Active, Inactive), we will introduce another
Selectcomponent fromreact-selectwith predefined options for these statuses. This will allow users to filter campaigns based on their current status.Here's how you can integrate this filter into your existing
CampaignsPagecomponent:-
Modify the State: Add a new state variable to keep track of the selected campaign status filter.
-
Add Status Options: Define the options for the campaign status filter.
-
Implement the Filter Logic: Update the filtering logic to consider the selected status.
Here’s the modified code:
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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, height: "38px", }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: () => ({ display: "none", }), input: (provided) => ({ ...provided, color: "#ffffff", }), }; const inputStyles = { backgroundColor: "#333333", color: "#ffffff", border: "1px solid #555555", outline: "none", boxShadow: "none", borderRadius: "4px", padding: "0 12px", height: "38px", fontSize: "1rem", width: "100%", "&:focus": { borderColor: "#777777", }, "&::placeholder": { color: "#bbbbbb", }, }; 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(null); const [sortOption, setSortOption] = useState(null); const [selectedStatus, setSelectedStatus] = useState({ value: "all", label: "All" }); const [categories, setCategories] = useState([]); const statusOptions = [ { value: "all", label: "All" }, { value: "active", label: "Active" }, { value: "inactive", label: "Inactive" }, ]; 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 status if (selectedStatus.value !== "all") { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.currentStatus === selectedStatus.value ); } // Filter by tag if (selectedTag && selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } // Filter by search term if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } // Sort campaigns switch (sortOption?.value) { 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, selectedStatus, 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-3"> <input type="text" className="form-control" style={inputStyles} placeholder="Search by title or description" value={search} onChange={(e) => setSearch(e.target.value)} /> </div> <div className="col-md-3"> <Select options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={true} placeholder="Select Tag" filterOption={(option, inputValue) => option.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-3"> <Select options={statusOptions} value={selectedStatus} onChange={setSelectedStatus} styles={selectStyles} isClearable={false} placeholder="Select Status" /> </div> <div className="col-md-3"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Key Additions
selectedStatusState: Added this to track which status filter is selected.statusOptionsArray: Defined the options for the status filter as All, Active, and Inactive.- Additional
SelectComponent: Implemented the status filter. - Updated Filtering Logic: Modified the filtering logic to include the status filter to determine which campaigns are shown.
This setup allows users to filter campaigns by their current status and should integrate seamlessly with the existing filters. Adjust further styling or logic if needed to fit the specific behavior and UI design of your app.
-
- User
make the default tag as All and status as Active
- Assistant
To set default values for the tag as "All" and the status as "Active", you can initialize these state variables with the corresponding object from the options you defined. Additionally, when setting default values for
react-select, make sure they are set to the option object, not just the string value.Here's how you can set these defaults:
-
Initialize Default States: Set the initial values of
selectedTagandselectedStatusto their respective default options. -
Ensure Correct Option Inclusing the Labels: Check that the default option labels match exactly what's defined in your options list.
Here’s how you can update your code to reflect these changes:
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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, height: "38px", }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: () => ({ display: "none", }), input: (provided) => ({ ...provided, color: "#ffffff", }), }; const inputStyles = { backgroundColor: "#333333", color: "#ffffff", border: "1px solid #555555", outline: "none", boxShadow: "none", borderRadius: "4px", padding: "0 12px", height: "38px", fontSize: "1rem", width: "100%", "&:focus": { borderColor: "#777777", }, "&::placeholder": { color: "#bbbbbb", }, }; 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(null); const [selectedStatus, setSelectedStatus] = useState({ value: "active", label: "Active" }); const [categories, setCategories] = useState([]); const statusOptions = [ { value: "all", label: "All" }, { value: "active", label: "Active" }, { value: "inactive", label: "Inactive" }, ]; 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 status if (selectedStatus.value !== "all") { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.currentStatus === selectedStatus.value ); } // Filter by tag if (selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } // Filter by search term if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } // Sort campaigns switch (sortOption?.value) { 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, selectedStatus, 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-3"> <input type="text" className="form-control" style={inputStyles} placeholder="Search by title or description" value={search} onChange={(e) => setSearch(e.target.value)} /> </div> <div className="col-md-3"> <Select options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={false} placeholder="Select Tag" filterOption={(option, inputValue) => option.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-3"> <Select options={statusOptions} value={selectedStatus} onChange={setSelectedStatus} styles={selectStyles} isClearable={false} placeholder="Select Status" /> </div> <div className="col-md-3"> <Select options={[ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]} value={sortOption} onChange={(option) => setSortOption(option)} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Key Changes
- Default Value for Tags: Initialized
selectedTagwith{ value: "all", label: "All" }. - Default Value for Status: Initialized
selectedStatuswith{ value: "active", label: "Active" }. - Ensure
isClearableFlag: For both tag and status filters, setisClearabletofalseto avoid accidental clearing of selections.
With these changes, the tag filter will default to "All", and the status filter defaults to "Active", while still allowing users to modify them. Adjust further if more specific default behaviors or interactions are required.
-
- User
can i have the default value for sort also be set to Sort By
- Assistant
Certainly! To set a default value for the sort option as "Sort By," you can similarly initialize the
sortOptionstate. You’ll want to make sure this default is consistent with what's available in your options list for sorting.Here’s how you can set the default state for sorting alongside tags and status:
-
Initialize Default Sort State: Set
sortOptionto the default object corresponding to the "Sort By" option. -
Ensure the Option Matches Exactly: Ensure that the label of the default option matches one defined in the sorting options list.
Here's how the updated code would look:
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"; const selectStyles = { control: (provided) => ({ ...provided, backgroundColor: "#333333", borderColor: "#555555", color: "#ffffff", boxShadow: "none", "&:hover": { borderColor: "#777777", }, height: "38px", }), menu: (provided) => ({ ...provided, backgroundColor: "#333333", }), singleValue: (provided) => ({ ...provided, color: "#ffffff", }), option: (provided, state) => ({ ...provided, color: "#ffffff", backgroundColor: state.isFocused ? "#444444" : "#333333", "&:hover": { backgroundColor: "#555555", }, }), placeholder: (provided) => ({ ...provided, color: "#bbbbbb", }), dropdownIndicator: (provided) => ({ ...provided, color: "#ffffff", "&:hover": { color: "#bbbbbb", }, }), indicatorSeparator: () => ({ display: "none", }), input: (provided) => ({ ...provided, color: "#ffffff", }), }; const inputStyles = { backgroundColor: "#333333", color: "#ffffff", border: "1px solid #555555", outline: "none", boxShadow: "none", borderRadius: "4px", padding: "0 12px", height: "38px", fontSize: "1rem", width: "100%", "&:focus": { borderColor: "#777777", }, "&::placeholder": { color: "#bbbbbb", }, }; 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({ value: "none", label: "Sort By" }); const [selectedStatus, setSelectedStatus] = useState({ value: "active", label: "Active" }); const [categories, setCategories] = useState([]); const statusOptions = [ { value: "all", label: "All" }, { value: "active", label: "Active" }, { value: "inactive", label: "Inactive" }, ]; const sortOptions = [ { value: "none", label: "Sort By" }, { value: "goalAmount", label: "Goal Amount" }, { value: "goalAmountPercentage", label: "Goal Amount Percentage" }, { value: "participants", label: "Number of Participants" }, ]; 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 status if (selectedStatus.value !== "all") { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.currentStatus === selectedStatus.value ); } // Filter by tag if (selectedTag.value !== "all") { updatedCampaigns = updatedCampaigns.filter((campaign) => campaign.tags.includes(selectedTag.value) ); } // Filter by search term if (search) { updatedCampaigns = updatedCampaigns.filter( (campaign) => campaign.title.toLowerCase().includes(search.toLowerCase()) || campaign.description.toLowerCase().includes(search.toLowerCase()) ); } // Sort campaigns switch (sortOption?.value) { 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, selectedStatus, 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-3"> <input type="text" className="form-control" style={inputStyles} placeholder="Search by title or description" value={search} onChange={(e) => setSearch(e.target.value)} /> </div> <div className="col-md-3"> <Select options={categories} value={selectedTag} onChange={setSelectedTag} styles={selectStyles} isClearable={false} placeholder="Select Tag" filterOption={(option, inputValue) => option.label.toLowerCase().includes(inputValue.toLowerCase()) } /> </div> <div className="col-md-3"> <Select options={statusOptions} value={selectedStatus} onChange={setSelectedStatus} styles={selectStyles} isClearable={false} placeholder="Select Status" /> </div> <div className="col-md-3"> <Select options={sortOptions} value={sortOption} onChange={setSortOption} styles={selectStyles} isClearable={false} placeholder="Sort By" /> </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;Key Changes
- Default Initialization for Sort: Setup
sortOptionto{ value: "none", label: "Sort By" }. - **Sort Options Defined in
sortOptionsArray: Ensures that the default value is part of the options list presented to users. isClearableFlag: Kept itfalsefor the sort as well, so the dropdown doesn't reset to an empty state accidentally.
These adjustments ensure that each filter initializes with a sensible default, allowing users to interact with the filters seamlessly right from the start.
-