How to add show more and show less button and render items according to them in react native

Viewed 260

I want to render my 10 items at a time and if there are extra items then show more button should be displayed below and if the user clicks it then 10 more should be displayed and so on. I have the property that tells me if there are items for the next page and if it is null then show more button should not be displayed. I don't know how to do it. I am new to react native and I will be very thankful if someone helps me to get out of this situation.

2 Answers

This code will display show more button only if shouldBeDisplayed is true.

shouldBeDisplayed is the prop which tell whether to show 10 more or not.

return {
  <View>
    {shouldBeDisplayed && <Button>show more</Button>}
  </View>
}

Will this be helpful?

import React, { useEffect, useState } from 'react';
import { Button, Text, View, } from 'react-native';

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];

export default function App() {
  const [isMore, setIsMore] = useState(false);
  const [showingItems, setShowingItems] = useState([]);

  useEffect(() => {
    setShowingItems([...items.slice(0, 10)]);
    if (items.length >= 10) {
      setIsMore(true);
    }
  }, []);

  const handleMore = () => {
    setShowingItems(items.slice(0, showingItems.length + 10))
    if (showingItems.length + 10 > items.length) {
      setIsMore(false);
    }
  }

  return (
    <View>
      {showingItems.map((x) => (
        <Text key={x}>{x}</Text>
      ))}

      {isMore && <Button title="More..." onPress={handleMore} />}
    </View>
  );
};

I created the above without that property. If you need to add it, you can do it like this

  useEffect(() => {
    setShowingItems([...items.slice(0, 10)]);
    setIsMore(yourProperty);
  }, []);
Related