import { useEffect, useState, memo, useMemo, useCallback } from "https://esm.sh/react";
import ReactDOM from "https://esm.sh/react-dom";
const fruits = [
'apple',
'banana',
'coconut',
'dragon fruit',
'eggplant',
'fig'
];
const shuffle = (array) => {
for(let i=0; i<array.length-1; i++) {
const randomIndex = Math.floor(Math.random() * array.length);
[array[i], array[randomIndex]] = [array[randomIndex], array[i]];
}
return array;
};
const Search = memo(({onChange}) => {
console.log('Search rendered');
return (
<div class="input-group mb-3">
<input
type="text"
class="form-control"
placeholder="Type your fruits"
onChange={(e) => onChange(e.target.value)} />
</div>
);
})
function App() {
const [allfruits, setAllFruits] = useState(fruits);
const handleSearch = useCallback((keywords) => {
setAllFruits(fruits.filter(fruit => fruit.toLowerCase().includes(keywords.toLowerCase())));
}, []);
return (
<>
<div class="search-group">
<Search onChange={handleSearch} />
{}
<button class="btn btn-outline-secondary" type="button" onClick={() => setAllFruits([...shuffle(allfruits)])}>Shuffle</button>
</div>
<ol class="fw-bolder">
{allfruits.map(fruit => <li>{fruit.charAt(0).toUpperCase() + fruit.slice(1)}</li>)}
</ol>
</>)
}
ReactDOM.render(<App />, document.querySelector("#app"));
View Compiled