Home > other >  How to give hide/show feature to certain components when it is mapped in react-native
How to give hide/show feature to certain components when it is mapped in react-native

Time:10-12

I am getting certain response from api:

[
    {   
        "name": "cds",
        "user_id": "1b625caf-9bea-4846-bdec-0cbcd76149cf"
    },
    {   
        "name": "asd",
        "user_id": "1b625caf-9bea-4846-bdec-0cbcd76149cf"
    },
    {
        "name": "qee",
        "user_id": "1b625caf-9bea-4846-bdec-0cbcd76149cf"
    },
    {
        "name": "cbb",
        "user_id": "1b625caf-9bea-4846-bdec-0cbcd76149cf"
    },
    {
        "name": "rty",
        "user_id": "1b625caf-9bea-4846-bdec-0cbcd76149cf"
    },
]

And I am using a component to show the details of this api:

<TouchableOpacity>
    <Text>Toggle</Text>
</TouchableOpacity>

{upcoming.map((item: any, key: any) => (
    <>
        <UpComingComponent
            name={item.name}
        />
    </>
))}

I am able to map the component successfully, But I need to have a feature, where initially user can see only two mapped UpComingComponent, and when user clicks on toggle, user should see all the mapped UpComingComponent, and when he again clicks on toggle, user show again only see two UpComingComponent.

I know how to have hide/show a component, but my problem is I have show two components initially, then toggle, show all the components, and again toggle, show only two components.

CodePudding user response:

You can use Array.slice and combine it with a state variable for toggle:

const [toggle, setToggle] = useState(false)

<TouchableOpacity onPress={() => setToggle(t => !t)}>
    <Text>Toggle</Text>
</TouchableOpacity>

{toggle ? upcoming.map((item: any, key: any) => (
    <>
        <UpComingComponent
            name={item.name}
        />
    </>
)) : upcoming.slice(0,2).map() => ...}

CodePudding user response:

You could filter the list for the first two items based on their index.

upcoming
.filter((item, index) => (!showAll ? index < 2 : true))
.map((item) => (
  <>
    <UpComingComponent name={item.name} />
  </>
));
  • Related