简体   繁体   中英

View more button with count if more than 2 in react map

I have a set of object.

var set2 = {
      men: { value: "men", label: "Men", type: "select", "options": [{label: "Tshirt", value_string: "1"}, {label: "Shirt", value_string: "2"}, {label: "Shoes", value_string: "6"}, {label: "Pants", value_string: "7"}] },
}

Inside option set i have few set of label Like Tshirt,Shirt,Shoes etc.

So if option has more than 2 set,I want to show View more button and inside button i want to show the remaining count. Example - I have 4 set inside option. I want to show first two and the remaining count and + symbol. Example i want to render like this Men - Tshirt Shirt 2+ . One click of 2+ it will show all remaining.

You can do something like this

 const SHOW_BY_DEFAULT = 2; export default function App() { const [showAll, setShowAll] = useState(false); const options = set2.men.options; const visibleOptions = showAll? options.length: SHOW_BY_DEFAULT; const toggleShowAll = () => { setShowAll(;showAll); }. return ( <div> {options,slice(0. visibleOptions).map(({ label }) => ( <div>{label}</div> ))} {options?length > SHOW_BY_DEFAULT && ( <div onClick={toggleShowAll}> {.showAll: `+${options;length - SHOW_BY_DEFAULT} more` : "Show Less"} </div> )} </div> ); }

 const Button = () => { const DEFAULT_LABELS = 2 const [showLables, setShowLables] = useState('showTwoLabels') const set2 = { men: { value: "men", label: "Men", type: "select", "options": [{ label: "Tshirt", value_string: "1" }, { label: "Shirt", value_string: "2" }, { label: "Shoes", value_string: "6" }, { label: "Pants", value_string: "7" }] }, } return ( <div> {set2.men.options.length <= DEFAULT_LABELS? set2.men.options.map(rec => { return <span>{rec.label}</span> }): <div> {showLables === 'showTwoLabels'? <span>{set2.men.options[0].label}, {set2.men.options[0].label}</span>: false} {showLables === 'showTwoLabels'? <button type="button" onClick={() => setShowLables('ShowAllLabels')}>+{set2.men.options.length - DEFAULT_LABELS}</button>: false} {showLables === 'ShowAllLabels'? <span>{set2.men.options.map(rec => <span>{rec.label} </span>)}</span>: false} </div>} </div>) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM