I want to reload an array of objects and make it appear based on the search input value.
For example, there's a search input and a list of reviews(title + comment).
When the user types "a" in the search input, the list will be reloaded and give you the lists that includes "a" in the title. And the items that doesn't include "a" in the title, will not be appeared.
When the user types "ab" in the search input, the list will be reloaded and give you the lists that includes "ab" in the title. And the items that doesn't include "ab" in the title, will not be appeared.
You can take a look at my current mini project here : https://distracted-golick-f00481.netlify.app/
You can add a review list and it will be saved into local storage. The list will be sorted by alphabetically and higher rank.
==========
Reviews.js ( that includes review lists )
import React, { useState } from "react";
import Header from "./Header";
import Review from "./Review";
import Input from "./Input";
const Reviews = ({ books, initialData }) => {
const combinedBooks = initialData.concat(books);
const [myBooks, setMyBooks] = useState(combinedBooks);
const [searchTerm, setSearchTerm] = useState("");
// sort by rank
let sorted = combinedBooks.sort((a, b) => {
return b.score - a.score;
});
// sort by alphabetical order
let newSorted = sorted.sort(function (a, b) {
let fa = a.title.toLowerCase(),
fb = b.title.toLowerCase();
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
});
// sort by rank then alphabetically
let newerSorted = [...newSorted].sort((a, b) => {
return b.score - a.score;
});
// Reload the data based on the search input value.. BUT How?
return (
<section style={{ border: "3px solid green" }}>
<Header title="Book Review Lists" />
{/* search input to find the book review by title */}
<form>
<Input
smallTitle=""
placeholder="find the review by title"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</form>
<h1>{searchTerm}</h1>
{newerSorted.map((review) => {
const { id, title, comment, score } = review;
return (
<Review key={id} title={title} comment={comment} score={score} />
);
})}
</section>
);
};
export default Reviews;
You can filter right inline before mapping the newerSorted
array for reviews that have the searchTerm
value included in their title
property.
{newerSorted.filter(({ title }) => title.toLowerCase().includes(searchTerm.toLoweCase()))
.map(({ id, title, comment, score }) => (
<Review key={id} title={title} comment={comment} score={score} />
))
}