pablosichert / react-truncate

React component for truncating multi-line spans and adding an ellipsis.
https://www.webpackbin.com/bins/-Kw6QnAkjmv1OD6Of-ZD
ISC License
587 stars 129 forks source link

ReadMore sample code issue #26

Closed SepiaGroup closed 7 years ago

SepiaGroup commented 7 years ago

the sample code has an issue:

the state is set as

this.state = {};

but this will default to 1 line since

lines={this.state.readMore && lines}

will always be false.

i fixed this and added a read more/less toggle

nice control btw saved me a ton of time thx.

`import React, {Component, PropTypes} from 'react'; import Truncate from 'react-truncate';

class ReadMoreText extends Component { constructor(...args) { super(...args);

    this.state = {readMore: true};

    this.toggleLines = this.toggleLines.bind(this);
}

toggleLines(event) {
    event.preventDefault();

    this.setState({
        readMore: !this.state.readMore
    });
}

render() {
    let {children, moreText, lessText, lines, style, styleMore, styleLess} = this.props;

    const divStyle = {
        width: '100%',
        wordWrap: 'break-word'
    };

    return (
        <div style={{...divStyle, ...style}}>
            <Truncate
                lines={this.state.readMore && lines}
                ellipsis={(
                    <span>... <a style={styleMore} onClick={this.toggleLines}>{moreText}</a></span>
                )}
            >
                {children}
            </Truncate>
            {lessText && !this.state.readMore && <span>&nbsp;<a style={styleLess || styleMore} onClick={this.toggleLines}>{lessText}</a></span>}
        </div>
    );
}

}

ReadMoreText.defaultProps = { lines: 3, moreText: 'more', lessText: 'less' };

ReadMoreText.propTypes = { children: PropTypes.node.isRequired, text: PropTypes.node, lines: PropTypes.number };

export default ReadMoreText;`

pablosichert commented 7 years ago

Thank you, fixed the sample code and added a demo.