search

Home  >  Q&A  >  body text

Use React to write filtering functions

<p>I want to create a filter function that fires when an input value event is received in react useState, but when I start typing I can't see it doing anything. This is my Search component</p> <pre class="brush:php;toolbar:false;">export function Search({categories, onSearch}){ const [searchText, setSearchText] = useState(''); const filterCategories = () => { const filteredCategories = categories.filter(category => category.name.toLowerCase().includes(searchText.toLowerCase()) ); onSearch(filteredCategories); }; const handleInputChange = event => { setSearchText(event.target.value); filterCategories(); }; return ( <div className="flex items-center"> <form className='flex space-x-1' > <input type="text" className="block w-full px-4 py-2 text-purple-700 bg-white border rounded-full focus:border-purple-400 focus:ring-purple-300 focus:outline-none focus:ring focus:ring -opacity-40" placeholder="Search..." value={searchText} onChange={handleInputChange} /> </form> </div> ) }</pre> <p>Then use</p> here <pre class="brush:php;toolbar:false;">const Layout = ({ categories, children }) => { const [filteredCategories, setFilteredCategories] = useState(categories); const handleSearch = (filteredCategories) => { setFilteredCategories(filteredCategories); }; return ( <div> {/* ... */} <Search categories={categories} onSearch={handleSearch} /> {/* ... */} {children} </div> ); }; export default Layout;</pre> <p>Then this component is used in the Home component</p> <pre class="brush:php;toolbar:false;">export default function Home({ posts, categories }) { return ( <Layout categories={categories}> <div className="mt-20"> <main className="flex flex-col justify-center items-center h-screen pt-10 pb-30"> {/* Render post */} </main> </div> </Layout> ); }</pre> <p>Is there anything I should do to make it work? </p>
P粉596191963P粉596191963544 days ago608

reply all(1)I'll reply

  • P粉431220279

    P粉4312202792023-08-17 14:42:05

    In the Layout component, you are passing the value of categories to your Search component, you may want to pass filteredCategories

    const Layout = ({ categories, children }) => {
      const [filteredCategories, setFilteredCategories] = useState(categories);
    
      const handleSearch = (filteredCategories) => {
        setFilteredCategories(filteredCategories);
      };
    
      return (
        <div>
          {/* ... */}
          <Search
            categories={filteredCategories} // 这里
            onSearch={handleSearch}
          />
          {/* ... */}
          {children}
        </div>
      );
    };
    
    export default Layout;

    (filteredCategories is not used, which makes you feel like nothing happened)

    reply
    0
  • Cancelreply