Whenever I try to search, I can type only the letters which are similar to the one of the titles. If any letter is different I lose focus from input. It used to work normally before, but Idk what happened now. Any suggestions?
After starting to type on search input:
When I type a letter which is not in the title:
Code:
JavaScript
x
68
68
1
if (props.items.length === 0) {
2
return (
3
<div className="files-list center">
4
<Card>
5
<h2>No files found.</h2>
6
</Card>
7
</div>
8
);
9
} else if (
10
props.items.filter(
11
(file) =>
12
file.title.toLowerCase().includes(searchInput) ||
13
file.title.toUpperCase().includes(searchInput)
14
).length === 0
15
) {
16
return (
17
<div className="filesList">
18
<div className="search">
19
<input
20
type="text"
21
placeholder="Search Files"
22
onChange={(event) => setSearchInput(event.target.value)}
23
/>
24
</div>
25
<Card>
26
<h2>No files found.</h2>
27
</Card>
28
</div>
29
);
30
}
31
32
return (
33
<React.Fragment>
34
<div className="filesList">
35
<div className="actionsBtn">
36
<NavLink to="/add-file" className="addFileBtn" title="Add File">
37
<FontAwesomeIcon icon={faPlus} />
38
</NavLink>
39
<input
40
type="text"
41
placeholder="Search Files"
42
onChange={(event) => setSearchInput(event.target.value)}
43
/>
44
</div>
45
<ul className="files-list">
46
{props.items
47
.filter(
48
(file) =>
49
file.title.toLowerCase().includes(searchInput) ||
50
file.title.toUpperCase().includes(searchInput)
51
)
52
.map((file) => (
53
<FilesPostItem
54
key={file.id}
55
id={file.id}
56
title={file.title}
57
file={file.file}
58
creator={file.creator.name}
59
description={file.description}
60
creatorId={file.creator}
61
onDelete={props.onDeleteFile}
62
/>
63
))}
64
</ul>
65
</div>
66
</React.Fragment>
67
);
68
Advertisement
Answer
What I think happens is, your “default” return form the beginning gets reset by the return in the “if else”. So the Input is a new DOM Element and loses focus.
You might want to add something like this to your default return and remove your “if else” statement.
JavaScript
1
30
30
1
<ul className="files-list">
2
{props.items
3
.filter(
4
(file) =>
5
file.title.toLowerCase().includes(searchInput) ||
6
file.title.toUpperCase().includes(searchInput)
7
)
8
.map((file) => (
9
<FilesPostItem
10
key={file.id}
11
id={file.id}
12
title={file.title}
13
file={file.file}
14
creator={file.creator.name}
15
description={file.description}
16
creatorId={file.creator}
17
onDelete={props.onDeleteFile}
18
/>
19
))}
20
</ul>
21
{props.items
22
.filter(
23
(file) =>
24
file.title.toLowerCase().includes(searchInput) ||
25
file.title.toUpperCase().includes(searchInput)
26
).length > 0 &&
27
<Card>
28
<h2>No files found.</h2>
29
</Card>
30
}
What does this do? It adds the “No files found” message to your default return and shows it only, if items is empty.
But i am pretty sure, there is a better way to do this.