Skip to main content

handleCategoryClick and handleSearchChange in React app are not retaining the funcionality across different components [duplicate]

The handleCategoryClick and handleSearchChange functions function correctly on the landing page. The navigation to the Testing or Articles components also works as expected.

Once in the Testing component, I can see the content "Hello" along with the <div className="nav-scroller py-1 mb-2 custom-class1"> that contains the categories and the search bar. Unfortunately, if I try to use the handleCategoryClick function within the Testing component, it does not work. The same issue occurs with the search bar as well, where typing something does not trigger any action.

Another issue is that when I click on any category, such as "Mexico" it displays the corresponding cards as expected. However, if I try to use the search bar, it doesn't work properly. It only shows me the results from the selected category. I passes the functions as props to the components, still do not work.

What I expect is that when I navigate to the Testing component, I should be able to search for something else and have the content of Testing hidden. Instead, I should see the cards based on what I type. The same applies to filtering categories. The content of Testing should be hidden, and the cards should be displayed according to the selected category.

 import React, { useState } from 'react';
import './App.css'
import Footer from './components/footer/Footer'
import filteredData from './components/data/filteredData';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';




function Testing({ handleCategoryClick, handleSearchChange }) {
  return (
    <div>
      <h1>Hello</h1>
    </div>
  );
}

function Articles({ handleCategoryClick, handleSearchChange }) {
  return (
    <div>
      <h1>Wasabito</h1>
    </div>
  );
}


function App() {
  const itemsPerPage = 9;
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');

   const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  }; 

  const handleCategoryClick = (category) => {
    setSelectedCategory(category);
    setCurrentPage(1);
  };

  const handleSearchChange = (event) => {
    setSearchTerm(event.target.value);
    setCurrentPage(1);
  };

  const filteredCards = filteredData.filter((item) => {
    const { category, text, description } = item;
    const lowerCaseSearchTerm = searchTerm.toLowerCase();
    return (
      (!selectedCategory || selectedCategory === 'All' || category === selectedCategory) &&
      ( category.toLowerCase().includes(lowerCaseSearchTerm) || 
        text.toLowerCase().includes(lowerCaseSearchTerm) ||
        description.toLowerCase().includes(lowerCaseSearchTerm))
    );
  });

  const totalCards = filteredCards.length;
  const totalPages = Math.ceil(totalCards / itemsPerPage);

  const indexOfLastCard = currentPage * itemsPerPage;
  const indexOfFirstCard = indexOfLastCard - itemsPerPage;
  const currentCards = filteredCards.slice(indexOfFirstCard, indexOfLastCard);
  const pageNumbers = Array.from({ length: totalPages }, (_, i) => i + 1);


  return (
    <Router>
      <div>        
        {selectedCategory === null && (
          <div className="p-3 mb-2 bg-primary text-white" 
            style=>
            Mas Verificaciones
          </div>
        )}
        
        <div className="nav-scroller py-1 mb-2 custom-class1">
          <nav className="nav d-flex justify-content-between px-3">
            <h2><a href="/"><img src="logo.png"  alt=" "/></a></h2>          
            {["Estados Unidos", "Mexico", "America Latina", "Resto del Mundo", "Covid-19", "Salud", "Medio Ambiente", "Guerra en Ucrania"].map((cat) => (
              <span
                className={`nav-link-second p-2 d-none d-md-block ${selectedCategory === cat ? "active" : ""}`}
                key={cat}
                style=
                onClick={() => handleCategoryClick(cat)}
              >
                {cat}
              </span>
            ))}
          </nav>
        </div>
        
        <div className="container">
          <div className="row">
            <div className="col-md-12 mb-3">
              <input
                type="text"
                className="form-control"
                placeholder="Search..."
                value={searchTerm}
                onChange={handleSearchChange}             
              />
            </div>
          </div>
        </div>     
              
        <Routes>
          <Route
            path="/"
            element={
              <>
                <div className="container">
                  <div className="row">
                    {currentCards.map((item) => (
                      <div className="col-md-4 mb-3" key={item.id}>
                        <div className="card">
                          <div className="card-body">
                            <div className="frame-color"></div>
                            <p className="card-text">{item.category}</p>
                            <p className="card-text">{item.description}</p>
                            <Link to={item.pagePath} className="btn btn-primary">
                              {item.text}
                            </Link>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
  
                <nav aria-label="...">
                  <ul className="pagination justify-content-center">
                    <li className={`page-item ${currentPage === 1 ? 'disabled' : ''}`}>
                      <a
                        className="page-link"
                        href="#"
                        onClick={() => setCurrentPage(currentPage - 1)}
                        tabIndex="-1"
                      >
                        Previous
                      </a>
                    </li>
                    {pageNumbers.map((number) => (
                      <li
                        key={number}
                        className={`page-item ${currentPage === number ? 'active' : ''}`}
                      >
                        <a
                          className="page-link"
                          href="#"
                          onClick={() => setCurrentPage(number)}
                        >
                          {number}
                        </a>
                      </li>
                    ))}
                    <li
                      className={`page-item ${currentPage === totalPages ? 'disabled' : ''}`}
                    >
                      <a
                        className="page-link"
                        href="#"
                        onClick={() => setCurrentPage(currentPage + 1)}
                      >
                        Next
                      </a>
                    </li>
                  </ul>
                </nav>       
              </>
            }
          />
          <Route path="/testing/:id" element={<Testing handleCategoryClick={handleCategoryClick} handleSearchChange={handleSearchChange} />} />
          <Route path="/articles/:id" element={<Articles handleCategoryClick={handleCategoryClick} handleSearchChange={handleSearchChange} />} />
        </Routes>

        <Footer />
      </div>
    </Router>
  );
}


export default App; 

//components/data/filteredData.js
const filteredData = [
  {
    id: 1,
    category: "Mexico",
    pagePath: "/articles/1",
    text: "Learn More",
    description: "loren ipsum loren ipssum loren ipsum"
  },
  {
    id: 2,
    category: "Estados Unidos",
    pagePath: "/testing/1",
    text: "Learn More",
    description: "loren ipsum loren ipssum loren ipsum"
  },]

I passed the functions as props to the components, I change this code without success.

const filteredCards = filteredData.filter((item) => {
  const { category, text, description } = item;
  const lowerCaseSearchTerm = searchTerm.toLowerCase();
  return (
    (!selectedCategory ||
      selectedCategory === "All" ||
      category === selectedCategory) && // <-- this conditional
    (category.toLowerCase().includes(lowerCaseSearchTerm) ||
      text.toLowerCase().includes(lowerCaseSearchTerm) ||
      description.toLowerCase().includes(lowerCaseSearchTerm))
  );
}); for this one 
const filteredCards = filteredData.filter((item) => {
  const { category, text, description } = item;
  const lowerCaseSearchTerm = searchTerm.toLowerCase();
  return (
    (!selectedCategory ||
      selectedCategory === "All" ||
      category === selectedCategory) || // <-- be more inclusive
    (category.toLowerCase().includes(lowerCaseSearchTerm) ||
      text.toLowerCase().includes(lowerCaseSearchTerm) ||
      description.toLowerCase().includes(lowerCaseSearchTerm))
  );
});
Via Active questions tagged javascript - Stack Overflow https://ift.tt/tIM3nLv

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data