Skip to content

Instantly share code, notes, and snippets.

@marufsiddiqui
Created October 20, 2020 13:51
Show Gist options
  • Save marufsiddiqui/c4c6e88f34342b6a256120404db60a30 to your computer and use it in GitHub Desktop.
Save marufsiddiqui/c4c6e88f34342b6a256120404db60a30 to your computer and use it in GitHub Desktop.
useShowMore React hook
import React, { useCallback, useState } from "react";
import "./styles.css";
const useShowMore = ({ items = [], initialVisibleItems = 4 }) => {
const [filteredItems, setFilteredItems] = useState(
items.slice(0, initialVisibleItems)
);
const [expanded, setExpanded] = useState(false);
const hasMoreItems = items.length > initialVisibleItems;
const showMore = useCallback(() => {
setFilteredItems(items);
setExpanded(true);
}, [items]);
const showLess = useCallback(() => {
setFilteredItems(items.slice(0, initialVisibleItems));
setExpanded(false);
}, [items, initialVisibleItems]);
// console.log(filteredItems);
return {
filteredItems,
hasMoreItems,
showMore,
showLess,
expanded
};
};
const items = [1, 2, 3, 4, 5];
export default function App() {
const {
filteredItems,
hasMoreItems,
showMore,
showLess,
expanded
} = useShowMore({
items
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<dl>
{filteredItems.map((i) => (
<dd key={i}>{i}</dd>
))}
</dl>
{hasMoreItems && !expanded && (
<button onClick={showMore}>Show More</button>
)}
{hasMoreItems && expanded && (
<button onClick={showLess}>Show Less</button>
)}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment