Reputation: 1871
What I needed was something like that shown in the picture. I need to show certain names and if the names list exceeds more than 2 rows I need to show +n others
. If the user clicks +n others
the list needs to be expanded to show all the others.
Is there any component available in react to get this result? I have seen it on a number of websites but don't know what they are called.
I could write the component myself but the difficult part would be how many names to show before i show the +n others. I can only show 2 rows initially and each name can be of variable length. So in one case, a single name may take up the entire 1st row and in others, i may be able to fit 3 names.
Upvotes: 2
Views: 88
Reputation: 741
You have to store the state of the list see it's expanded or not.
Something like this should help.
import React, { useEffect, useState } from "react";
const myList = ({ list }) => {
const MAX_COUNT = 5;
const [isExpended, setIsExpended] = useState(false);
useEffect(() => {
if (list.length <= MAX_COUNT) {
setIsExpended(true);
}
}, [list]);
const expend = () => {
setIsExpended(true);
};
return (
<>
<div>
{list.map((item, i) =>
(isExpended === false && i < MAX_COUNT) || isExpended === true
? item.text
: null
)}
</div>
{isExpended === false ? (
<button onClick={expend}>+ {list.length - MAX_COUNT} others</button>
) : null}
</>
);
};
export default myList;
If you want to stick with 2 rows on any conditions there will be 2 approach to set the dynamic MAX_COUNT
:
1: if you have a constant value for box-sizing and fonts and etc:
You can compute outerWidth of each elements (with box-sizing and elements length) and set a real MAX_COUNT
based on that.
2: if you have responsive design:
you can render component with initial MAX_COUNT
but hide contents with visibility: hidden
and then computing outerWidth of each elements would be more realistic and much more easier.
in this scenario you have to fix the container height to prevent it from extending too much, just set a constant height to it, also you can change it after you get a real MAX_COUNT
. now you can show contents with no worries.
Upvotes: 1