Skip to content

Instantly share code, notes, and snippets.

@AudyOdi
Last active May 27, 2017 16:52
Show Gist options
  • Select an option

  • Save AudyOdi/95c380a1e8041fa5dc931f5d90d9fef2 to your computer and use it in GitHub Desktop.

Select an option

Save AudyOdi/95c380a1e8041fa5dc931f5d90d9fef2 to your computer and use it in GitHub Desktop.
Ellipsis Component
// @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>;
}
}
}
}
@AudyOdi
Copy link
Author

AudyOdi commented May 27, 2017

how to use it:
image

the result will be
image

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment