Search code examples
javascriptreactjsmath

How to always get the same number from a changable number?


i have an array which stores books, and i want to show a fixed number of those books, the array length is changable, so how would i always end up with the same number ? based on the length of the array? and increase that number each time a button is clicked ?

how i would want the functionality of my page:

"the shown items is 10, and always 10, and then everytime the button is clicked i would show 10 more, if the last books aren't less than 10, then i would show them

what i want is this:

function BooksContainer(){
const itemLength = booksData.length

const [booksShown,setBooksShown] = useState(fixedItemLength)

return (
   booksData.slice(0,booksShown).map(()=>{
      return <Books>
    })

   <button onClick={setBooksShown((prev)=> prev + fixedItemLength)}>Show More</button>)
}


writing the question, i think im approaching the problem wrongly, thank you in advance


Solution

  • …the shown items is 10, [?], then everytime the button is clicked i would show 10 more, if the last books aren't [are ?] less than 10, then i would show them

    Since you want to show 10 at the start but increase by 10 upon successive clicks, this should work. It will increase what gets shown (by 10) each time the button gets clicked.

    Aside: Shouldn’t Books take a prop? The booksData is expected to be an array of books or isn’t it? Won’t Books take data from this array which it will render? I added that in the code with highlights but you could remove it if you want.

    function BooksContainer()
    {
        let pageSize = 10;
        let start = 0;
        const [end, setEnd] = useState(pageSize - 1);
        return (
            <>
                {
                    booksData.slice(start, end).map((book, index) => (
                        <Books book={book} key={index} />
                    )
                }
                <button
                disabled={end > booksData.length}
                onClick={
                    () => setEnd(prev => prev + pageSize - 1)
                }>Show More</button>
            </>
        )
    }

    Couldn’t resist to nitpick but it should be Book not Books.