From 8c6d806d47e97e1edcf54a70573d1c85f12ed5f6 Mon Sep 17 00:00:00 2001 From: Severiano Badajoz Date: Wed, 27 May 2020 13:53:45 -0700 Subject: [PATCH] support children --- client/src/components/util/truncate.js | 63 ++++++++++++++++---------- 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/client/src/components/util/truncate.js b/client/src/components/util/truncate.js index 9d103ca4..af372c7c 100644 --- a/client/src/components/util/truncate.js +++ b/client/src/components/util/truncate.js @@ -1,4 +1,4 @@ -import React, { Component } from "react"; +import React, { Component, cloneElement } from "react"; import { Tooltip, Position } from "@blueprintjs/core"; import pixelWidth from "string-pixel-width"; @@ -53,27 +53,44 @@ export default class Truncate extends Component { render() { const { children, size, fontSize } = this.props; - const originalString = children[0].text; - const truncatedString = this.maybeTruncateString( - originalString, - size, - fontSize - ); - children[0].text = truncatedString; - return ( - - {children} - - ); + // Truncate only support a single child with a text child + + if ( + React.Children.count(children) === 1 && + React.Children.count(children.props?.children) === 1 + ) { + const originalString = children.props.children; + const truncatedString = this.maybeTruncateString( + originalString, + size, + fontSize + ); + // Only make tooltip if string has to be truncated + if (truncatedString) { + // clone children, changing the children(text) to the truncated string + const newChildren = React.Children.map(children, (child) => + cloneElement(child, { + children: truncatedString, + "data-truncated": true, + }) + ); + return ( + + {newChildren} + + ); + } + return children; + } + throw Error("Only pass a single child with inner text to Truncate"); } }