Home > Software engineering >  React js, limiting post shown
React js, limiting post shown

Time:07-16

Hi i am just making a blog using next js and graph cms,i just know how to limit the number posts shown, for example if i have 50 posts in the backend i just need 1 post to show, like how to limit it?

here, this is what i am talking about

const posts = [
    {title: 'Sample Post 1', description: 'Lorem ipsum dolor sit amet'},
    {title: 'Sample Post 2', description: 'Lorem ipsum dolor sit amet'}
];

<div>
       {
        posts.map((posts, index) => (
          <div>
            <h1>{posts.title}</h1>
             <p>{posts.description}</p>
             
           </div>
        ))
       }
    </div>

if i run this all the post will be show, is there anyway to limit in JS?

CodePudding user response:

you can use slice

{
   posts.slice(0,1).map((posts, index) => (
     <div>
        <h1>{posts.title}</h1>
        <p>{posts.description}</p>       
     </div>
     ))
}

CodePudding user response:

You can use .slice(0, 1).

Example:

export default function Posts() {
  const posts = [
    { title: "Sample Post 1", description: "Lorem ipsum dolor sit amet" },
    { title: "Sample Post 2", description: "Lorem ipsum dolor sit amet" },
    { title: "Sample Post 2", description: "Lorem ipsum dolor sit amet" },
    { title: "Sample Post 2", description: "Lorem ipsum dolor sit amet" },
    { title: "Sample Post 2", description: "Lorem ipsum dolor sit amet" },
    { title: "Sample Post 2", description: "Lorem ipsum dolor sit amet" },
  ];
  return (
    <div>
      {posts.slice(0, 1).map((posts, index) => (
        <div key={index}>
          <h1>{posts.title}</h1>
          <p>{posts.description}</p>
        </div>
      ))}
    </div>
  );
}
  • Related