DEV Community

Fatima Alam
Fatima Alam

Posted on

Search Component React

import "./styles.css";
import React, { useEffect } from "react";
import { useState } from "react";
import axios from "axios";

export default function App() {
  const URL = `https://jsonplaceholder.typicode.com/todos`;
  const [todoList, setTodoList] = useState([]);
  const [text, setText] = useState("");
  const [filteredTodos, setFilteredTodos] = useState([]);

  useEffect(() => {

    const todos = async () => {
      let todo = await fetch(URL);
      let data = await todo.json();
      console.log(data);
      setTodoList(data);
      setFilteredTodos(data);
    };
    todos();
  }, []);
  // console.log(todoList);

  const changeText = (e) => {
    setText(e.target.value);
    // console.log(todoList.length);
    let filteredTodo = todoList.filter((todo) => {
      return todo.title.toLowerCase().includes(e.target.value.toLowerCase());
    });
    console.log("filtered", filteredTodo);
    setFilteredTodos(filteredTodo);
  };

  return (
    <div className="App">
      <input
        type="text"
        value={text}
        onChange={(e) => {
          changeText(e);
        }}
      ></input>

      <ul>
        {filteredTodos.map((todo) => {
          return <li key={todo.id}>{todo.title}</li>;
        })}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)