From 637263f73fbfe0fbb2bf4a60a4a7456767cc3655 Mon Sep 17 00:00:00 2001 From: chaofan <chaofan1801@gmail.com> Date: Mon, 4 Oct 2021 21:17:14 +1100 Subject: [PATCH] refactor: convert text ellipsis to functional component --- src/components/TextEllipsis/index.jsx | 96 ++++++++++----------------- 1 file changed, 36 insertions(+), 60 deletions(-) diff --git a/src/components/TextEllipsis/index.jsx b/src/components/TextEllipsis/index.jsx index d2e3a1795..cb9577a57 100644 --- a/src/components/TextEllipsis/index.jsx +++ b/src/components/TextEllipsis/index.jsx @@ -4,66 +4,42 @@ import React from 'react'; import Popover from '../Popover'; import './styles.scss'; -class TextEllipsisComponent extends React.PureComponent { - static propTypes = { - children: PropTypes.node.isRequired, - /** - * Can use `placement` and `trigger` props from <a href="/popover">Popover</a> to control popover. - */ - popoverProps: PropTypes.shape(_.pick(Popover.propTypes, ['placement', 'trigger'])), - }; +const TextEllipsis = ({ popoverProps, children }) => { + const containerRef = React.useRef(); + const [truncated, setTruncated] = React.useState(false); - static defaultProps = { - popoverProps: { - placement: 'top', - trigger: 'hover', - }, - }; + React.useEffect(() => { + const nextTruncateState = containerRef.current.scrollWidth > containerRef.current.clientWidth; - constructor(props) { - super(props); - - this.container = React.createRef(); - } - - state = { - truncated: false, - }; - - componentDidMount() { - this.setTruncate(); - } - - componentDidUpdate() { - this.setTruncate(); - } - - setTruncate() { - const nextTruncateState = this.container.current.scrollWidth > this.container.current.clientWidth; - if (this.state.truncated !== nextTruncateState) { - this.setState({ - truncated: nextTruncateState, - }); + if (truncated !== nextTruncateState) { + setTruncated(nextTruncateState); } - } - - render() { - const { popoverProps } = this.props; - const { truncated } = this.state; - - return ( - <Popover - {...popoverProps} - {...(truncated === false ? { triggers: 'disabled' } : {})} - popoverContent={this.props.children} - className="aui--text-ellipsis-wrapper" - > - <div data-testid="text-ellipsis" className="text-ellipsis-component" ref={this.container}> - {this.props.children} - </div> - </Popover> - ); - } -} - -export default TextEllipsisComponent; + }, [truncated]); + + return ( + <Popover + {...popoverProps} + {...(truncated === false ? { triggers: 'disabled' } : {})} + popoverContent={children} + className="aui--text-ellipsis-wrapper" + > + <div data-testid="text-ellipsis" className="text-ellipsis-component" ref={containerRef}> + {children} + </div> + </Popover> + ); +}; + +TextEllipsis.propTypes = { + children: PropTypes.node.isRequired, + popoverProps: PropTypes.shape(_.pick(Popover.propTypes, ['placement', 'trigger'])), +}; + +TextEllipsis.defaultProps = { + popoverProps: { + placement: 'top', + trigger: 'hover', + }, +}; + +export default TextEllipsis;