I am creating a react app with an array showing list of items, trying to add a read more and hide items if the list item count is more than 3.
my codesandbox is here below. could any one help me with this
https://codesandbox.io/s/eloquent-gates-xtkr4y?file=/src/comp.js
CodePudding user response:
You could render it conditionally. So you render the first three items of the array with a button that says read more
. If you click on the button it changes the state of the conditional render to true
, rendering the whole array instead of the first 3 items. Once you click on read more
you could change it to hide
with another conditional, using the same state. Once you press on hide
again it will set the state to false
and render the first three items again.
A code example:
import "./styles.css";
import { useState } from "react";
export default function App() {
const [toggleHide, setToggleHide] = useState(false);
const array = ["apple ", "pear ", "banana ", "melon ", "grapes "];
const newArray = array.slice(0, 3);
const [buttonText, setButtonText] = useState("read more");
function handleClick() {
if (!toggleHide) {
setButtonText("hide");
} else {
setButtonText("read more");
}
setToggleHide(!toggleHide);
}
return (
<div className="App">
{!toggleHide ? <h1>{newArray}</h1> : <h1>{array}</h1>}
<button onClick={() => handleClick()}>{buttonText}</button>
</div>
);
}
Codesandbox link: https://codesandbox.io/s/toggle-readme-w0c7id?file=/src/App.js
CodePudding user response:
maybe this will help you
import React, {useEffect, useState} from "react";
const Comp = ({car}) => {
const [count, setCount] = useState([]);
const [more, setMore] = useState(false);
useEffect(() => {
let arr = [];
for (let i = 0, t = Math.floor(Math.random() * 5); i < t; i ) {
arr.push(i);
}
return () => {
arr.length >= 3 ? setMore(true) : setMore(false)
setCount(arr);
}
}, []);
const doSomething = () => {
console.log('Your Logic Here')
}
return (
<div>
{count?.length > 0 &&
count.map((i) => {
return <div key={i}>{i}</div>;
})}
{more && <button onClick={doSomething}> More List </button>}
</div>
);
// return <li>{car.name}</li>;
};
export default Comp;