patrik-piskay / react-truncate-markup Goto Github PK
View Code? Open in Web Editor NEW✂️ React component for truncating JSX markup
License: MIT License
✂️ React component for truncating JSX markup
License: MIT License
Warning: Failed prop type: Invalid prop
children
of typeobject
supplied toTruncateMarkup
, expected a single ReactElement.
My Code
const Title = ({ style, line, text }) => (
<TruncateMarkup lines={line} tokenize={'words'}>
<div>
<div style={style} >
{text}
</div>
</div>
</TruncateMarkup>
);
and
const Location = ({ style, line, text }) => (
<TruncateMarkup lines={2} tokenize={'words'}><div><span>{`Location ${location}`}</span></div></TruncateMarkup>
);
I see this warning message as above in console IE11. TruncateMarkup still works correctly for IE , but let me know please if it's can take a negative effect on my text in IE11
tiles-by-social-edge-events-0.0.1-10e1fa-dev.zip
?
It would be interesting if we can pass markup via string (e.g. the child element using dangerouslySetInnerHTML)
Please re-publish package with typescript declaration file included
Hi,
Thanks for the amazing plugin!
However we have an issue when Chrome's Google Translate is being used.
Reproducible here https://clx8h.csb.app/ (Source: https://codesandbox.io/s/react-truncate-markup-google-translate-clx8h)
The root caused seems to be deriving from facebook/react#11538 (comment) Not sure if there's a fix for this?
Hello! First of all, thanks for awesome component!
And here is a demo of the bug: https://codesandbox.io/s/2zk3z45kqj.
Could you suggest some workaround?
Dosen't work with
dangerouslySetInnerHTML={{
__html: props.text,
}}
https://codesandbox.io/s/truncatemarkup-demo-forked-r9lhtp?file=/index.js
Hello, great library, useful for many common scenarios. After some time I have a need to extend the functionality in a way that we could use React components in TruncateMarkup
.
Common use case: display a list of components, either created with react html markup or actual react (class/functional) components, and display only as many components as possibly - based on their size.
I understand there is no way how to possibly split react components. That's not my intention.
This option was already discussed in some older PR
<TruncateMarkup>
<div>
<span truncateAtom>{ /* ... can have custom Components inside */ }</span>
<span truncateAtom>{ /* ... can have more DOM nodes inside */ }</span>
{/* or possibly with a custom component provided by this lib */}
<TruncateMarkupAtom>{ /* ... can have custom Components inside */ }</TruncateMarkupAtom>
<TruncateMarkupAtom>{ /* ... can have more DOM nodes inside */ }</TruncateMarkupAtom>
</div>
</TruncateMarkup>
This seems to be a easy solution as long as there is good way to indicate that a element/Component should not be analyzed any further.
Props types stay the same thus it doesn't introduce breaking changes.
1.1 Is a component preferred over some custom prop? Or maybe let's just see what ever is easier to do..
1.2 In either way, I think we'll need to check children (=potential Atom) props - that doesn't sounds great, but to some extend that is already happening in the lib. Right now, I am not aware of a way how to easily and reliably check if a node is create by a specific React component. Or is there a way ?
tokenize
Optiona new tokenize
option could be aslo a way, but the more I think about it, the more complex it is. Either to document what that option would and wouldn't do, or to provide multiple tokenize
options for slightly different usecases. The complexity of the code handling these options would get just more complicated than it needs to be.
I am willing to do a PR. I'd like to reach some kind of agreement here before doing that so the time is well spent 😄
I have a use case where in the content composed of tags is truncated when reaching 3 lines/rows. Each tags can be added or removed by the user after the initial load (mounted). I use the value of "truncated" from the onTruncate
callback to handle some outside logic that's why it's important to get the correct value of it.
I was expecting that when the component truncates the content and renders the ellipsis, it will call the onTruncate
callback with a value of "true" since it was truncated. Take note that this happens after the initial load and when the content is being updated.
Please take a look at this sample demo: https://codesandbox.io/s/lucid-joliot-lljlit?file=/src/App.js
The index.d.ts file has not been updated with the new onAfterTruncate property (which causes warnings when using the library from TypeScript)
(May I also say, not that it matters, onAfterTruncate is a really odd name :) onTruncate would have been a bit more concise)
Great little component - thanks. Your home page does discuss conditional rendering, but any advice on using the component in a TabContainer? Every time a tab not containing the component is selected, the warning below is triggered:
console.warn('ReactTruncateMarkup: number of currently rendered lines: ' + computedLines + ', not truncating...\n It may be caused by target element not being visible at the time of computation.');
I've had to comment it out since in dev it clogs up the console ;-)
Best, Keith
Describe the bug
Under the flex layout, reducing the width of the parent container results in incomplete truncated content.
To Reproduce
https://codesandbox.io/s/ccti1?file=/index.js
Reproduce Step
Hello again!
Just a quick feature suggestion this time. How about keepWholeWords
prop, that - if set to true
- would make react-truncate-markup
keep full words and not cut the in half? At the moment I keep getting truncated words, i.e. se
(whole word is sed
):
In this example this flag set to true
could then render something like this:
So basically: if the word is going to be cut in half, just omit it in the result.
I tried to prepare a PR with this, but I got lost in the source code of this repo. I might try again during weekend though
Hi,
I wonder if there is a way to suppress console error logs if React components are passed as children? I am happy with the scenario where there is not truncating if content contains React components.
Thanks,
Jelena
I am using this control to trim rich text editor output html to 5 lines but not working. I am using JSX attribute dangerouslySetInnerHTML to set the HTML inside a div control. My HTML content is simply consist of divs and paragraph.
<TruncateMarkup lines={6}> <div> <div dangerouslySetInnerHTML={{__html: this.state.data.Body}}> </div> </div> </TruncateMarkup>
This makes the entire react component go blank. Following is error on browser console.
Invariant Violation: Minified React error #185;
I'm developing a React extension and using "react-truncate-markup" to truncate the html from the api. Works fine in Chrome and does exactly what I need, but unfortunately fails in FIrefox.
I'm getting TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
Full error:
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
pa7React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
pa7React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
react-dom.production.min.js:4408
pa7React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73
TypeError: "'getComputedStyle' called on an object that does not implement interface Window."
exports computedStyle.commonjs.js:9 exports line-height.js:12 componentDidMount4React
unstable_runWithPriority scheduler.production.min.js:274 Is12React
q content.js:82 q content.js:73 ~~~~
I noticed that when I used a div
(block) element inside TruncateMarkup (other than the initial element that wraps the text to be truncated), the truncation was happening one update behind what it should, and also truncating the text a character too soon.
I managed to create an isolated Stackblitz example of this here: https://stackblitz.com/edit/truncate-markup-jsx-bug
I think it's understandable that using block elements inside TruncateMarkup wouldn't work, so I'm not sure if this would be classified as a bug per se. Maybe it should just be an FYI/Warning in the Readme?
I got the error Warning: Each child in an array or iterator should have a unique "key" prop. See https://fb.me/react-warning-keys for more information.
while using react-truncate-markup
with custom ellipsis being callback function. I attach the component causing the problem.
Describe the bug
Hello,
I've noticed a bug where it fails to truncate at all when the string is a single long word. Add whitespace at any point and everything is fine though.
To Reproduce
https://codesandbox.io/s/truncatemarkup-demo-forked-ys7f4?file=/index.js
Describe the bug
This does not run in a test environment. Either get an error saying Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
or it just doesn't render anything into jsdom.
To Reproduce
https://codesandbox.io/s/icy-tree-rr3dq
next-dev.js?3515:25 Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.
* Move data fetching code or side effects to componentDidUpdate.
* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state
Please update the following components: TruncateMarkup
Hello!
This component is fantastic, great work!
I was wondering, is there was a way to set the position of the ellipsis? Currently, it seems to appear at the end of the line (which make sense). But is there a way for us to maybe set it to cut off the line 50% of the way?
e.g.
"Current version"
Here is my text block. I set my lines to 3 and
by the time I finish this text here we will be
on the third line and it ends at t... Read More.
"Cut Off Version"
Here is my text block. I set my lines to 3 and
by the time I finish this text here we will be
on the th... Read More.
Thanks!
Hi!
Just a quick suggestion: how about adding a callback (onAfterTruncate
or sth) that would be fired after the text has been truncated? It could be helpful to recalculate dynamically positioned elements after the text is truncated...
Describe the bug
I am trying to use this package in Ionic React but it only show the first letter of the paragraph
To Reproduce
This is the repo to see the issue https://github.com/LFTroya/expenses
Type error: No overload matches this call.
Overload 1 of 2, '(props: TruncateProps | Readonly<TruncateProps>): TruncateMarkup', gave the following error.
Type '{ children: Element; lines: number; ellipsis: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TruncateMarkup> & Readonly<TruncateProps>'.
Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<TruncateMarkup> & Readonly<TruncateProps>'.
Overload 2 of 2, '(props: TruncateProps, context: any): TruncateMarkup', gave the following error.
Type '{ children: Element; lines: number; ellipsis: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TruncateMarkup> & Readonly<TruncateProps>'.
Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<TruncateMarkup> & Readonly<TruncateProps>'.
24 | <div className="prose-sm mt-2">
25 | {truncate ? (
> 26 | <TruncateMarkup
| ^
27 | lines={10}
28 | ellipsis={
29 | <ReadMoreEllipsis toggle_truncate={toggle_truncate} />
Image
As you can see in the image, I want each sentence to go to the next line similar to the textbox, but it gets attached to the previous sentence and forms a paragraph. The truncation is working perfectly, but I want it to look something like this:
My name is Karan
I am a developer
I love programming and K-Dramas... See More
How can I achieve this?
Code
const readMoreEllipsis = (
<span>
...{' '}
<span onClick={toggleTruncate} style={showButtonStyles}>
{showButtonText}
</span>
</span>
);
if (isTruncated) {
return (
<TruncateMarkup lines={lines} ellipsis={readMoreEllipsis}>
<div style={textProps}>{text}</div>
</TruncateMarkup>
);
}
return (
<div style={textProps}>
{text}
<span onClick={toggleTruncate} style={hideButtonStyles}>
{hideButtonText}
</span>
</div>
);
Reproducable in onTruncate callback
case from the README
When shrinking the box, text goes to the second line even though lines={1}
was passed into the props.
When expanding, text is truncated even though there is enough room.
Seems like something to do with the setState
called in onTruncate
, when I removed it things were fine.
Seriously, be civilized and make it optional.
When trying to use TruncateMarkup.Atom
with TypeScript I get the following error message:
Property 'Atom' does not exist on type 'typeof TruncateMarkup'
.
Looking at index.d.ts
, I see it is missing the export/definition of Atom
.. Could you please help me to overcome that issue?
Hei,
Upon using the translate functionality of the browser (Right click - Translate to..) then:
BROWSER
Chrome
Before I look into creating a solution, I was wondering if you would be open to having a boolean prop called something like withTitle
(open to naming suggestions). If the prop is set (to true), then when the content inside the element is truncated, it sets the title
attribute to the original text.
The purpose of this is so that when text is truncated, you can still hover over the text to see the original text in the browser-default tooltip.
Thoughts?
This does NOT need an immediate attention, but ..
Earlier in some minor version of react@16, componentWillReceiveProps
and a few other methods were flagged as deprecated
. The intention is to remove them completely in react@17.
In this package, both componentWillReceiveProps
and componentDidUpdate
do a lot of stuff, and I have no idea how complex it could be (if actually possible) to replace it by the new lifecycle methods. Btw. there is a polyfill for the new methods in older versions of react https://github.com/reactjs/react-lifecycles-compat
Is there any plan to use the new lifecycle methods ?
As I said, this does not need to solved right now. However, it would be nice to have some idea about what's going to happen with this package once the release of react@17 is happening.
I'm using a button with a flex layout whose label is a comma delimited list of other labels. I've using the characters tokenize strategy, but the only way to get the word-wrap to correctly truncate the text is to include a whitespace between those labels. This seems to be due to the wordWrap: 'break-word' styling is applied regardless of tokenizing strategy (https://github.com/parsable/react-truncate-markup/blob/master/src/index.js#L322) whereas a 'characters' tokenizing strategy ought to use 'anywhere' instead.
To Reproduce
https://codesandbox.io/s/truncatemarkup-demo-z3zq4?file=/index.js
Truncation occurs differently depending on the markup around the string being truncated, often behaving as if it ignores lines
completely.
Examples:
<TruncateMarkup lines={3}>
<div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Maecenas mattis
turpis nec erat gravida, ut dignissim erat auctor.
Phasellus tincidunt tristique urna, sed luctus nisl
vulputate nec. Proin lacus diam, semper vel mattis
in, pretium a dolor. Morbi gravida ante neque, vitae
sodales turpis consequat quis. Fusce mi arcu,
pretium ac imperdiet id, consequat quis libero.
Vivamus sollicitudin venenatis urna, nec venenatis
diam vehicula id. Phasellus commodo blandit iaculis.
Pellentesque magna mauris, tincidunt quis viv
</p>
</div>
</TruncateMarkup>
Lines = 1, lines = 2:
Lines = 3:
Lines = 4:
Lines = 5:
Etc.. from lines = 5 and up, you basically get (lines - 3) actual output to infinity (will overflow a fixed height container).
If a span is used instead of p, you get roughly the same behavior, but get (lines - 1) when lines >= 3.
Behavior is only as expected and documented when the top div just has the bare string in it with no other markup.
Unfortunately, I do not get a lot of control over the markup being truncated here and I don't think I can effectively rewrite the markup dynamically to strip things like p and span (etc). Any suggestions very welcome here.
The below minimal enzyme test fails with error message "Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of WrapperComponent
.":
import { mount } from 'enzyme';
import * as React from 'react';
import Truncate from 'react-truncate-markup';
describe('truncate', () => {
it('renders', () => {
mount(<Truncate>foo</Truncate>);
});
});
My project is in TypeScript (not sure if it matters?) and my dependencies:
Hi, anyone tried to use this library with Storybook?
I'm getting
TypeError: Cannot read property '_ownerDocument' of undefined
at TruncateMarkup.componentDidMount (../../node_modules/react-truncate-markup/lib/index.js:171:73)
on each snapshot, even if their component do not import TruncateText from react-truncate-markup
Describe the bug
I am using truncateMarkup.Atom and have custom ellipsis which takes some width, sometimes ellipsis overflowed and wrapped up in next line which ideally should come in that line itself
Describe the bug
When the content to truncate is number an error occurs.
To Reproduce
<TruncateMarkup lines={1} ...>
<div>
{1}
</div>
</TruncateMarkup>
Here's the code sandbox https://codesandbox.io/s/react-truncate-markup-issue-4xgwc?file=/src/App.js
TruncateMarkup doesn't render after the data is changed dynamically.
No changes is applied to data after TruncateMarkup has loaded.
<TruncateMarkup lines={3}>
<div>
{Some Content}
</div>
</TruncateMarkup>
Hello
I've noticed a bug where it fails to truncate at all when the children have multi list child. and one of the string are too long.
There is the demo url:https://codesandbox.io/s/truncatemarkup-demo-forked-frksr
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.