Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution #758

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ that will suggest people matching an entered text.
- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save.
- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_autocomplete/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://hma-3.github.io/react_autocomplete/) and add it to the PR description.
- Don't remove the `data-qa` attributes. It is required for tests.

## Troubleshooting
Expand Down
72 changes: 12 additions & 60 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,73 +1,25 @@
import React from 'react';
import React, { useState } from 'react';
import './App.scss';
import { peopleFromServer } from './data/people';

import { Person } from './types/Person';
import { Dropdown } from './components/Dropdown/Dropdown';

export const App: React.FC = () => {
const { name, born, died } = peopleFromServer[0];
const [selectedPerson, setSelectedPerson] = useState<Person | null>(null);

return (
<div className="container">
<main className="section is-flex is-flex-direction-column">
<h1 className="title" data-cy="title">
{`${name} (${born} - ${died})`}
{selectedPerson
? `${selectedPerson.name} (${selectedPerson.born} - ${selectedPerson.died})`
: 'No selected person'}
</h1>

<div className="dropdown is-active">
<div className="dropdown-trigger">
<input
type="text"
placeholder="Enter a part of the name"
className="input"
data-cy="search-input"
/>
</div>

<div className="dropdown-menu" role="menu" data-cy="suggestions-list">
<div className="dropdown-content">
<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-link">Pieter Haverbeke</p>
</div>

<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-link">Pieter Bernard Haverbeke</p>
</div>

<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-link">Pieter Antone Haverbeke</p>
</div>

<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-danger">Elisabeth Haverbeke</p>
</div>

<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-link">Pieter de Decker</p>
</div>

<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-danger">Petronella de Decker</p>
</div>

<div className="dropdown-item" data-cy="suggestion-item">
<p className="has-text-danger">Elisabeth Hercke</p>
</div>
</div>
</div>
</div>

<div
className="
notification
is-danger
is-light
mt-3
is-align-self-flex-start
"
role="alert"
data-cy="no-suggestions-message"
>
<p className="has-text-danger">No matching suggestions</p>
</div>
<Dropdown
selectedPerson={selectedPerson}
onSelect={setSelectedPerson}
/>
</main>
</div>
);
Expand Down
96 changes: 96 additions & 0 deletions src/components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React, { FC, useState, useCallback, useMemo } from 'react';
import debounce from 'lodash.debounce';
import cn from 'classnames';

import { peopleFromServer } from '../../data/people';
import { Person } from '../../types/Person';
import { filterPeople } from '../../utils/filterPeople';
import { DropdownMenu } from '../DropdownMenu/DropdownMenu';

type Props = {
selectedPerson: Person | null;
onSelect: React.Dispatch<React.SetStateAction<Person | null>>;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think - this will be better and more readable, right?

Suggested change
onSelect: React.Dispatch<React.SetStateAction<Person | null>>;
onSelect: (person: Person | null) => void;

delay?: number;
};

export const Dropdown: FC<Props> = ({
selectedPerson,
onSelect,
delay = 300,
}) => {
const [query, setQuery] = useState('');
const [appliedQuery, setAppliedQuery] = useState('');
const [isActive, setIsActive] = useState(false);

// eslint-disable-next-line react-hooks/exhaustive-deps
const applyQuery = useCallback(debounce(setAppliedQuery, delay), []);

const filteredPeople = useMemo(
() => filterPeople(peopleFromServer, { appliedQuery }),
[appliedQuery],
);
Comment on lines +28 to +31

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change syntax and use it in the future(more readable)

Suggested change
const filteredPeople = useMemo(
() => filterPeople(peopleFromServer, { appliedQuery }),
[appliedQuery],
);
const filteredPeople = useMemo(() => (
filterPeople(peopleFromServer, { appliedQuery })
), [appliedQuery]);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll remember it, thanks, but here prettier changes it back


const visiblePeople = selectedPerson ? peopleFromServer : filteredPeople;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The key for list items is generated during render which is not a good practice. As per the article, it's better to generate unique keys for list items when the list is created.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useMemo?


const handleInputFocus = () => {
setIsActive(true);
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The handleInputFocus function is not following the recommended naming conventions for event handlers in React. According to the naming conventions, the function should be named onInputFocus.


const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value.trimStart());
applyQuery(event.target.value);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to make sure that filter won't be called if user entered spaces only. In the current implementation, if the user only enters spaces, the filter function will still be called. You should trim the input value before applying the filter.

onSelect(null);
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The handleInputChange function is not following the recommended naming conventions for event handlers in React. According to the naming conventions, the function should be named onInputChange.


const handleSelect = (person: Person) => {
onSelect(person);
setQuery(person.name);
setIsActive(false);
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The handleSelect function is not following the recommended naming conventions for event handlers in React. According to the naming conventions, the function should be named onSelectPerson.


return (
<>
<div
className={cn('dropdown', {
'is-active': isActive,
})}
>
<div className="dropdown-trigger">
<input
type="text"
placeholder="Enter a part of the name"
data-cy="search-input"
className="input"
value={query}
onFocus={handleInputFocus}
onChange={handleInputChange}
/>
</div>

{!!filteredPeople.length && (
<DropdownMenu
people={visiblePeople}
selectedPerson={selectedPerson}
onSelect={handleSelect}
/>
)}
</div>

{!filteredPeople.length && (
<div
className="
notification
is-danger
is-light
mt-3
is-align-self-flex-start
"
role="alert"
data-cy="no-suggestions-message"
>
<p className="has-text-danger">No matching suggestions</p>
</div>
)}
</>
);
};
6 changes: 6 additions & 0 deletions src/components/DropdownMenu/DropdownMenu.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@import '../../variables/colors';

.dropdown-item:hover {
background-color: $dropdown-backgrount-hover-color;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

syntax mistake

Suggested change
background-color: $dropdown-backgrount-hover-color;
background-color: $dropdown-background-hover-color;

cursor: pointer;
}
46 changes: 46 additions & 0 deletions src/components/DropdownMenu/DropdownMenu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { FC } from 'react';
import cn from 'classnames';
import './DropdownMenu.scss';
import { Person } from '../../types/Person';

type Props = {
people: Person[];
selectedPerson: Person | null;
onSelect: (person: Person) => void;
};

export const DropdownMenu: FC<Props> = ({
people,
selectedPerson,
onSelect,
}) => {
return (
<div className="dropdown-menu" role="menu" data-cy="suggestions-list">
<div className="dropdown-content">
{people.map(person => {
const { name, sex } = person;

return (
<div
key={person.slug}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Key generation on render is not recommended. This is because keys should be stable between multiple renders for performance reasons. You can read more about it here.

className={cn('dropdown-item', {
'has-background-grey-lighter': selectedPerson === person,
})}
data-cy="suggestion-item"
onClick={() => onSelect(person)}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a performance issue. You are creating a new function every time the component renders. This is not recommended. Instead, create a function inside the component that accepts a person as an argument and call this function in your onClick handler. This way, a new function is not created on every render.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The naming convention for event handlers in React suggests that the name should start with 'handle' and end with the type of event you are handling. In this case, a better name would be 'handleSelectPerson'. You can read more about the naming conventions here.

>
<p
className={cn({
'has-text-link': sex === 'm',
'has-text-danger': sex === 'f',
})}
>
{name}
</p>
</div>
);
})}
</div>
</div>
);
};
18 changes: 18 additions & 0 deletions src/utils/filterPeople.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Person } from '../types/Person';

export function filterPeople(
people: Person[],
{ appliedQuery }: { appliedQuery: string },
) {
let filteredPeople = [...people];

if (appliedQuery) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should check if appliedQuery is not only truthy, but also not just spaces. Currently, if a user enters spaces only, the filter function will be called unnecessarily. Consider using trim() method before the check to ensure that spaces only won't pass the condition.

const normalizedQuery = appliedQuery.toLocaleLowerCase().trim();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The toLocaleLowerCase() method is a good approach to make the search case-insensitive. However, please note that for some languages and locales, this method might not work as expected. If you plan to support multiple languages, you might need to use a library for more accurate case conversion.


filteredPeople = filteredPeople.filter(person =>
person.name.toLocaleLowerCase().includes(normalizedQuery),
);
}

return filteredPeople;
}
1 change: 1 addition & 0 deletions src/variables/colors.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
$dropdown-backgrount-hover-color: hsl(0, 0%, 96%);
Loading