I want to display only 10 list items from the property name "text" which is in one of a dataset object and give more button below that. On this button click I want to show remaining list items. I tried with the below code using useState hook but not getting the desired result, I know I'm doing something wrong. Any help would be appreciated.
import React, { useState } from 'react';
const ReadMoreReadLess = ({ children }) => {
const [ReadMoreShown, setReadMoreShown] = useState(false);
const toggleBtn = () => {
setReadMoreShown(prevState => !prevState)
}
return (
<div className='readMore_readLess'>
{children}
<button onClick={toggleBtn}>Read More</button>
</div>
)
}
export default ReadMoreReadLess
Below is one of the dataset object
const data = [
{
type: "Names",
text: [
{id: "1", info: "Audi"},
{id: "2", info: "BMW"},
{id: "3", info: "Chevrolet"},
{id: "4", info: "Citroen"},
{id: "5", info: "Hyundai"},
{id: "6", info: "Mercedes-Benz"},
{id: "7", info: "Renault"},
{id: "8", info: "Seat"},
{id: "9", info: "KIA"},
{id: "10", info: "Toyota"},
],
image: service_1,
},];
I'm displaying like this.
<div className="services__service__description">
<ReadMoreReadLess>
{text.map((t) => (
<ul>
<li key={t.id}>
{t.info}
</li>
</ul>
))}
</ReadMoreReadLess>
</div>
CodePudding user response:
this.state.current_page
equals 0 initially then get changed when you want to show more items
<div className="services__service__description">
<ReadMoreReadLess>
{text.slice(0, (this.state.current_page 1)*10).map((t) => (
<ul>
<li key={t.id}>
{t.info}
</li>
</ul>
))}
</ReadMoreReadLess>
</div>
CodePudding user response:
I did this changes to my code.
import React, { useState } from 'react';
const ReadMoreReadLess = ({ children }) => {
const [isReadMoreShown, setReadMoreShown] = useState(false);
const toggleBtn = () => {
setReadMoreShown((prevState) => !prevState)
}
return (
<div className='readMore_readLess'>
{isReadMoreShown ? children : children.slice(0, 5)}
<button onClick={toggleBtn}>Read More</button>
</div>
)
}
export default ReadMoreReadLess
Displaying it like this
<div className="services__service__description">
<ReadMoreReadLess>
{text.map((t) => (
<ul>
<li key={t.id}>
{t.info}
</li>
</ul>
))}
</ReadMoreReadLess>
</div>