Home > other >  HIde load more button when all items are from array displayed in react
HIde load more button when all items are from array displayed in react

Time:09-01

This should be easy but of course I can't figure it out :)

Basically I've implemented a "load more" button when there are more items to display from array but when it reaches the end, I'd like to hide it. The code below doesn't work and I have a feeling it's because it need to check the index of the array and if it's at the end, then hide the button but I am unsure of how to go about the syntax. Thanks

import { useState } from 'react'
import releases from "../data/releases.json";
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import '../main.css'

const Release = () => {
  // get first 12 items in array & load next 12 with "see more button"
  const STEP = 12;
  const [items, setItems] = useState(releases.slice(0, STEP));

  const loadMore = () => {
    setItems([...items, ...releases.slice(items.length, items.length   STEP)]);
  };

  return (
    <Wrapper>
      <div className="release fadein">
        {items.map((item, i) => (
          <div className="item" key={i}>
            <Link to={`/release/${item.id}`}>
              <img src={item.imageURL} alt={item.artist} />
            </Link>
          </div>
        ))}
{/* code that isn't working here */}
        {items ? <button onClick={loadMore} className="btn" > show more </button> : <button className="btn hidden" ></button>}
      </div>
    </Wrapper >
  )
}

CodePudding user response:

when the items are less than 12 the button will not be displayed

 {items ===0 ? <button onClick={loadMore} className="btn" > show more </button> : nul}
  
  • Related