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

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...