T
T
Tamila Suleimanova2021-07-19 21:07:28
React
Tamila Suleimanova, 2021-07-19 21:07:28

How can search be implemented in react?

import React, { useEffect, useState } from 'react'

function App() {
  // State
  const [peoples, setPeoples] = useState([])
  const [loading, setLoading] = useState(true)
  const [searchFilter, setSearch] = useState('')


  // Hooks
  useEffect(() => {
    loadPeoples()
  }, [])

  // Methods
  const loadPeoples = () => {
    fetch('https://swapi.dev/api/people/')
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        setPeoples(data.results)
        setLoading(false)
      })
  }
 
  
  // Renderx
  return (
    <div className="app py-5">
      <div className="container">

        <h1 className="display-1 mb-5">Star Wars Api</h1>
        <input type="text"
          className="form-control mb-4"
          placeholder="Search..."
          onChange={(e) => setSearch(e.target.value)}
        />
        {loading ? (
          <div>Loading...</div>
        ) : (
          <ul className="list-group">
            {peoples.map((man, idx) => (
              <li className="list-group-item" key={idx}>
              <div className="row">
                <div className="col-8">
                  <h3>{man.name}</h3>
                </div>
              </div>
            </li>
            ))}
          </ul>
        )}
      </div>
     
    </div>
  )
}

export {App}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-19
@0xD34F

Filter data using a user-supplied string:

const filteredPeople = people.filter(n => n.name.includes(searchFilter));

Use filter result for rendering instead of full data:
<ul className="list-group">
  {filteredPeople.map(n => (
    ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question