Home > Web Front-end > JS Tutorial > ExpandableText Components

ExpandableText Components

WBOY
Release: 2024-07-19 11:54:41
Original
1135 people have browsed it

ExpandableText Components

import { Typography } from "@mui/material";
import { useEffect, useRef, useState } from "react";

interface ExpandableTextProps {
    text: string;
    extendedText: string;
    numberOfLine: number;
}

const ExpandableText: React.FC<ExpandableTextProps> = ({ text, extendedText = "Description", numberOfLine = 3 }) => {
    const [expanded, setExpanded] = useState(false);
    const [maxHeight, setMaxHeight] = useState<string | number>('none');
    const contentRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (contentRef.current) {
            setMaxHeight(expanded ? contentRef.current.scrollHeight : `${numberOfLine * 1.5}em`);
        }
    }, [expanded, numberOfLine])

    const toggleExpand = () => {
        setExpanded((prev) => !prev);
    };

    return (
        <>
            <div
                ref={contentRef}
                style={{
                    overflow: 'hidden',
                    maxHeight: maxHeight,
                    transition: 'max-height 0.3s ease-in-out',
                }}
            >
                <Typography
                    component="p"
                    sx={{
                        fontSize: 12,
                        fontWeight: 700,
                        letterSpacing: 0.5,
                        display: '-webkit-box',
                        WebkitBoxOrient: 'vertical',
                        WebkitLineClamp: expanded ? 'unset' : numberOfLine,
                        textOverflow: 'ellipsis',
                        mt: 1,
                    }}
                >
                    {text}
                </Typography>
            </div>
            <span style={{ color: "blue", cursor: "pointer" }} onClick={toggleExpand}>
                {expanded ? `Collapse ${extendedText}` : `Expand ${extendedText}`}
            </span>
        </>
    );
};


export default ExpandableText;
Copy after login

The above is the detailed content of ExpandableText Components. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template