Last active
May 27, 2017 16:52
-
-
Save AudyOdi/95c380a1e8041fa5dc931f5d90d9fef2 to your computer and use it in GitHub Desktop.
Ellipsis Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // @flow | |
| import React, {Children} from 'react'; | |
| type Props = { | |
| maxStringLength: number; | |
| children?: React$Element<*>; | |
| }; | |
| let maxString = 13; | |
| export default function Elipsis(props: Props) { | |
| let {children, maxStringLength} = props; | |
| let components = []; | |
| maxString = maxStringLength || maxString; | |
| Children.forEach(children, (child) => { | |
| components.push(getComponent(child)); | |
| }); | |
| return ( | |
| <div> | |
| {components} | |
| </div> | |
| ); | |
| } | |
| function getComponent(child: React$Element<*>) { | |
| if (child) { | |
| if (Array.isArray(child)) { | |
| return Children.map(child, (grandChild) => { | |
| return getComponent(grandChild); | |
| }); | |
| } else { | |
| if (typeof child === 'string') { | |
| let string = ''; | |
| if (maxString <= 0) { | |
| return string; | |
| } | |
| string = child.slice(0, maxString); | |
| if (child.length >= maxString) { | |
| string = string + '...'; | |
| } | |
| maxString = maxString - string.length; | |
| return string; | |
| } else if (typeof child === 'object') { | |
| let {children, ...otherProps} = child.props; | |
| let Component = child.type; | |
| let value = getComponent(children); | |
| return <Component {...otherProps}>{value}</Component>; | |
| } | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use it:

the result will be
