← All tasksReact · Junior

Filter a list

Write a FilterList component that receives an array of strings items. Above the list there's a search input labelled Search.

The <ul> list shows only the strings that contain the typed text, ignoring case and spaces at the ends of the query. If nothing matches, show a No results paragraph instead of the list.

Tests (4)

  1. render(<FilterList items={['Apple', 'Banana', 'Cherry']} />);
    expect(screen.getAllByRole('listitem').map((li) => li.textContent)).toEqual(['Apple', 'Banana', 'Cherry']);
  2. render(<FilterList items={['Apple', 'Banana', 'Cherry']} />);
    fireEvent.change(screen.getByLabelText('Search'), { target: { value: 'an' } });
    expect(screen.getAllByRole('listitem').map((li) => li.textContent)).toEqual(['Banana']);
  3. render(<FilterList items={['Apple', 'Banana', 'Cherry']} />);
    fireEvent.change(screen.getByLabelText('Search'), { target: { value: ' AP ' } });
    expect(screen.getAllByRole('listitem').map((li) => li.textContent)).toEqual(['Apple']);
  4. render(<FilterList items={['Apple', 'Banana', 'Cherry']} />);
    fireEvent.change(screen.getByLabelText('Search'), { target: { value: 'xyz' } });
    expect(screen.getByText('No results')).toBeTruthy();
    expect(screen.queryAllByRole('listitem')).toHaveLength(0);