What I'm trying to achieve. Image sample here
Hi Guys I'm still learning and trying to truncate a long text but with few conditions. Let's say I have an array of 5 words, if the text is too long, it will need to truncate the text to accommodate the width of the container. But I wanted it to cut the whole word instead of just the letters. As example object of [one, two, three, four, five]
One, two, three, ... 2 (counter) I want this
One, two, three, fou ... 1 (counter) I don't want this
Below is what I have tried but I'm not sure where to go next also to make the counter dynamic based on truncated text number instead of an array length.
function App() {
const numbers = ["one", "two", "three", "four", "five"];
const testStyle = {
display: "flex",
justifyContent: "space-between",
background: "#D0D0D0",
padding: "6px 8px",
width: "150px",
whiteSpace: "nowrap",
};
const truncatedStyle = {
textOverflow: "ellipsis",
overflow: "hidden",
};
return (
<div className="App">
<div style={testStyle}>
<div style={truncatedStyle}>
{numbers.map((n, i) => (
<span>
{n}
{i === 4 ? "" : ", "}
</span>
))}
</div>
<div
style={{ background: "black", color: "white", padding: "2px 4px" }}
>
{numbers.length}
</div>
</div>
</div>
);
}
CodePudding user response:
One thing you can do is you can use useRef
and get those spans width, then check it
in a variable if it is greater than 150px
. if no the add the span, if yes then add , ...
then add the span width to the variable.
CodePudding user response:
You can modify **function App()**
using Vanilla Javascript you can achieve the same result in the form of String and then through String Interpolation you can render it on the HTML as going by Best Coding Practices all the logic part must be concluded in JS and HTML should be used only for view/rendering the data.
Example -
function App() {
var s = "";
var c = 0;
const numbers = ["one", "two", "three", "four", "five"];
for(var i =0 ; i< numbers.length;i ){
i>2 ? c : s = s numbers[i] ", ";
}
return numbers.length > 3 ? s ".." c : s;
}