My solution:
ExpandableText.tsx
import { useState } from "react";
interface Probs {
text: string;
maxChar: number;
}
const ExpandableText = ({ text, maxChar }: Probs) => {
const [innerText, setInnerText] = useState(text);
const handleClick = () => {
const newText =
innerText.length === maxChar + 3 ? text : text.slice(0, maxChar) + "...";
setInnerText(newText);
};
return (
<div>
<p> {innerText} </p>
<button onClick={handleClick}>
Read {innerText.length === maxChar + 3 ? "More" : "Less"}
</button>
</div>
);
};
export default ExpandableText;
App.tsx
import ExpandableText from "./components/ExpandableText";
const App = () => {
const text =
"Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel ipsa, est quaerat, nihil eveniet unde mollitia deserunt laborum quibusdam";
return (
<div>
<ExpandableText text={text} maxChar={15} />
<p></p>
</div>
);
};
export default App;