antd

Expand/Collapse with Ant Typography


Ant Design has a Typography library which is helpful in displaying text. One particularly helpful feature is the ability to "Expand" text. From the Ant documentation, you can display a paragraph as such:

enter image description here

Hitting "Expand" will produce the following:

enter image description here

The issue here, is that after you expand there is no option to "Collapse" the text back to what we had originally, which can be problematic. I have been looking through the Typography documentation here, but there is no mention of the ability to collapse. I was wondering if there was a way to achieve something like a "Collapse" using the Ant Typography library.

Another option that I have considered is the react-text-collapse library, however I am not sure it is a perfect solution.


Solution

  • Looks like ant design doesn't have default option to collapse the typography paragraph. You can request for the feature at ant design github.

    However you can achieve it with some state changes. Here is the sample link

    https://codesandbox.io/s/upbeat-jepsen-4h7ek

    class Demo extends React.Component {
      state = {
        expand: false,
        counter: 0
      };
    
      typoExpand = () => {
        this.setState({
          expand: true,
          counter: !this.state.expand
            ? this.state.counter + 0
            : this.state.counter + 1
        });
      };
    
      typoClose = () => {
        this.setState({
          expand: false,
          counter: !this.state.expand
            ? this.state.counter + 0
            : this.state.counter + 1
        });
      };
    
      renderParagraph() {
        return (
          <div key={this.state.counter}>
            <Paragraph
              ellipsis={{
                rows: 3,
                expandable: true,
                onExpand: this.typoExpand
              }}
            >
              Ant Design, a design language for background applications, is refined
              by Ant UED Team. Ant Design, a design language for background
              applications, is refined by Ant UED Team. Ant Design, a design
              language for background applications, is refined by Ant UED Team. Ant
              Design, a design language for background applications, is refined by
              Ant UED Team. Ant Design, a design language for background
              applications, is refined by Ant UED Team. Ant Design, a design
              language for background applications, is refined by Ant UED Team.
            </Paragraph>
          </div>
        );
      }
    
      render() {
        return (
          <div>
            {this.renderParagraph()}
            {this.state.expand && <a onClick={this.typoClose}>Close</a>}
          </div>
        );
      }
    }