Home Reference Source

application/components/common/word-counter.js

import React from 'react';
import PropTypes from 'prop-types';
import pluralize from 'pluralize';


function countWords(s){
    s = s.replace(/\n/g,' '); // newlines to space
    s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
    s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1

    return s.split(' ').length;
}

/**
 * Word counter
 */
class WordCounter extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            watchString: false,
            count: false
        };
    }

    componentWillMount() {
        this.setState({
            watchString: this.props.count,
            count: this.props.count ? countWords(this.props.count) : 0
        });
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            watchString: nextProps.count,
            count: nextProps.count ? countWords(nextProps.count) : 0
        });
    }

    render() {
        if (!this.state.count && !this.props.displayEmpty) {
            return (<span></span>);
        }

        let label = false;
        if (this.props.label !== false) {
            label = pluralize(
                this.props.label ? this.props.label : 'word',
                this.state.count
            );
        }

        return (
            <span className='word-counter'>{this.state.count}{label ? ' ' + label : ''}</span>
        );
    }
}

WordCounter.propTypes = {
    count: PropTypes.string,

    displayEmpty: PropTypes.bool,
    label: PropTypes.string
}

export default WordCounter;