Tengo un <p> con un párrafo dentro y un botón. Me gustaría mostrar 40 caracteres cuando hago clic en el botón. Y mostrar todo el párrafo si vuelvo a hacer clic en él.
Aquí está mi código:
const [showText, setShowText] = useState(false) <div> <ImCross onClick={() => setShowText(!showText)} /> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consectetur debitis deserunt dicta dignissimos est et excepturi facere facilis fugit id in, ipsa quae reiciendis repellendus suscipit unde veniam voluptas.</p> </div> <ImCross /> es el botón para ocultar y mostrar texto. Ahora estoy totalmente perdido sobre cómo puedo obtener la .length de <p> y cambiar el número que se muestra al hacer clic.
Alguna ayuda ?
Puede crear una función truncada y usarla cuando se haya hecho clic en el botón Mostrar más.
Encontré una función truncada de esta respuesta .
Por lo que su código podría ser algo como:
// create a function that only returns a certain amount of characters. // i've just used 5 as it's what the original stack question did const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input; function App() { // create a toggle state const [showTruncate, setShowTruncate] = useState(true); let content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consectetur debitis deserunt dicta dignissimos est et excepturi facere facilis fugit id in, ipsa quae reiciendis repellendus suscipit unde veniam voluptas"; // when the toggle is active, show the truncated text // if not, show the text in full. return ( <div className="App"> <button onClick={() => setShowTruncate(!showTruncate)}>Show more</button> <p>{showTruncate ? truncate(content) : content}</p> </div> ); }