I have React ponent, where I have some dynamic text:
...
let spanLength
return(
<SomeComp>
...
<span>Some static text: {someDynamicText}, {someAnotherText}</span>
...
</SomeComp>
)
How can I get the length of text inside span
element to a spanLength
variable?
I have React ponent, where I have some dynamic text:
...
let spanLength
return(
<SomeComp>
...
<span>Some static text: {someDynamicText}, {someAnotherText}</span>
...
</SomeComp>
)
How can I get the length of text inside span
element to a spanLength
variable?
2 Answers
Reset to default 8You can add a ref
to your span
let spanRef = React.createRef()
...
<span ref={spanRef}>Some static text: {someDynamicText}, {someAnotherText}</span>
Then the text length would simply be spanRef.current.textContent.length
Why not, first, pose the whole string? You can grab its length immediately after, and then render it.
const spanStr = `Some static text: ${someDynamicText}, ${someAnotherText}`;
const spanLength = spanStr.length;
return(
<SomeComp>
...
<span>{spanStr}</span>
...
</SomeComp>
)