Home Reference Source

application/components/common/character-counter.js

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

/**
 * Character counter
 */
class CharacterCounter extends React.Component {

    constructor(props) {
        super(props);

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

    shouldComponentUpdate(nextProps, nextState) {
        return (this.props.count != nextProps.count);
    }

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

    componentWillReceiveProps(nextProps) {
        this.setState({
            watchString: nextProps.count,
            count: nextProps.count ? nextProps.count.length : 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 : 'character',
                this.state.count
            );
        }

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

CharacterCounter.propTypes = {
    count: PropTypes.string,

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

export default CharacterCounter;