Home > Software engineering >  When Creating a search input in react
When Creating a search input in react

Time:02-04

When creating a search input in react it worked successfully but when removes search word from input it remove all data from array and return no thing

i need to search but when i done return array again

const [todos, setTodos] = useState([]);

const searchTodo = (todoitem) => {
 const searchedTodo = todos.filter((todo) => {
  if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) {
    return todo;
  }
});
setTodos(searchedTodo);

};

CodePudding user response:

You can either create a new variable for filtered todos or use it at body without any extra field.

First, let's take a took at the first solution:

const [todos, setTodos] = useState([]);
const [filteredTodos, setFilteredTodos] = useState([]);

const searchTodo = (todoitem) => {
  const searchedTodo = todos.filter((todo) => {
    if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) {
      return todo;
  }

  return searchedTodo;
});

useEffect(() => {
  setFilteredTodos(searchTodo(todoitem));
}, [todoitem]); \\ todoitem is the text you want to search with

The other way is just using the function in return body like below:

const [todos, setTodos] = useState([]);

const searchTodo = (todoitem) => {
  const searchedTodo = todos.filter((todo) => {
    if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) {
      return todo;
  }

  return searchedTodo;
});

return (
  <div>
    {searchTodo(todoitem).map(todo => (<div>{todo}</div>))}
  </div>
);

CodePudding user response:

Based on ldruskis comment:

const [todos, setTodos] = useState([]);
const [filtered, setFiltered] = useState([]);

const searchTodo = (todoitem) => {
 const searchedTodo = todos.filter((todo) => {
  if (todo.text.toLowerCase().includes(todoitem.toLowerCase())) {
    return todo;
  }
});
setFiltered(searchedTodo);

Then you add a conditional render such as:

{filtered.length > 0 ? <render filtered> : <render todos>
  •  Tags:  
  • Related