I m trying to do this effect on react-native
Desired result
Obtained result
This is my code but i actually miss the space between the line.
<Text>
<Text style={{color: '#fff', fontWeight: '600', fontSize: 26, backgroundColor: 'blue' }}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</Text>
</Text>
Using lineHeight
in your styling should do what you're looking for:
<Text>
<Text style={{color: '#fff', fontWeight: '600', fontSize: 26, backgroundColor: 'blue', lineHeight: 20 }}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</Text>
I was able to achieve this effect using a solution similar to what Travis White suggests above. Image of effect in action
It is by no means a perfect solution, and I'm almost certain there are use cases that I am not handling for, but here it is:
class HighlightText extends Component {
state = { lines: [] };
renderLines() {
let textString = this.props.children;
// splitOn is integer value. Enter expected max char count per line as prop
const splitOn = this.props.splitOn;
// Adds space to end of string, preventing cutoff of last word
const singleSpace = ' ';
textString = textString.concat(singleSpace);
const numOfLines = Math.ceil(textString.length / splitOn);
let lineStart = 0;
let lineEnd = textString.slice(0, splitOn).lastIndexOf(' ');
let fakeLineEnd = lineStart + splitOn;
/* multiplying x2 to handle for awkward splits before very long words
that can push content beyond the above calculated numOfLines */
for (i = 0; i < numOfLines * 2; i++) {
let line = textString.slice(lineStart, lineEnd);
// Adds spaces to start and end of already populated lines for visual padding
if (line.length > 0) {
line = singleSpace + line + singleSpace;
this.state.lines.push(line);
}
lineStart = lineEnd + 1;
fakeLineEnd = lineStart + splitOn;
lineEnd = textString.slice(0, fakeLineEnd).lastIndexOf(' ');
}
return this.state.lines.map((line, i) =>
<View
key={i}
style={{
marginTop: this.props.marginTop,
}}
>
<Text>
<Text
style={{
fontSize: this.props.fontSize,
color: this.props.color,
backgroundColor: this.props.backgroundColor
}}
>
{line}
</Text>
</Text>
</View>
);
}
render() {
return (
<View>
{this.renderLines()}
</View>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With