Home > Enterprise >  Possible to render components in reverse manner in JSX?
Possible to render components in reverse manner in JSX?

Time:12-02

In my Nextjs/React.js component I am rendering list of cards like this :

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
    <div className="lg:col-span-8 col-span-1">
      {posts.map((post, index) => (
        <PostCard post={post.node} key={post.title} />
      ))}
    </div>

I was wondering if it was possible to render these PostCards in a reverse manner; starting from the last index rather than the initial index? This is for my blog application and whenever I post a new PostCard I want the latest Post to be rendered on Top of the list instead of the bottom of the list.

CodePudding user response:

Just reverse the array first:

{posts.slice(0).reverse().map((post, index) => (
    <PostCard 
        key={ index } 
        post={ post.node } 
        key={ post.title } 
    />
))}

CodePudding user response:

whenever I post a new PostCard I want the latest Post to be rendered on Top of the list instead of the bottom of the list.

If you're currently doing this by adding to the end of an array, you can add to the start of it instead. For example, if you're doing this:

setPosts(prev => [...prev, { title: 'My New Post' }]);

Do this instead:

setPosts(prev => [{ title : 'My New Post' }, ...prev]);

If you can't change the way the array gets created (say, because some components want it in one order, and some in another), then you can create a new array in the right order, and then map over that. You may want to memoize this if the array isn't going to change often:

const reorderedPosts = useMemo(() => {
  return [...posts].reverse();
}, [posts]);

// ...
{reorderedPosts.map((post, index) => (
  <PostCard post={post.node} key={post.title} />
))}

This can also easily be enhanced to let you change the order via a state, if you need to:

const [shouldReverse, setShouldReverse] = useState(false);
const reorderedPosts = useMemo(() => {
  if (shouldReverse) {
    return [...posts].reverse();
  } else {
    return posts;
  }
}, [posts, shouldReverse])

// ...
{reorderedPosts.map((post, index) => (
  <PostCard post={post.node} key={post.title} />
))}
  • Related