Reputation: 8906
I have a text and I would like to highlight some of its parts, like:
This is a well-written paragraph of text.
This is a well-written paragraph of text.
5-8 23-31
Highlights are defined as an array of arrays:
[[5, 8], [23, 31]]
How to convert source text (a string) into renderable JSX item:
(<Text>This <Hl>is a</Hl> well-written <Hl>paragraph</Hl> of text.</Text>)
the React Native way?
P.S. Hl is simply a JSX-macros:
const Hl = (props) => <Text style={{fontWeight: 'bold'}}>{props.children}</Text>
Upvotes: 1
Views: 151
Reputation: 1122
Created a simple function that takes text and array of values to transform. Run the below snippet for example
function transform(text,arr){
let transformObj = arr.reduce((all, item) => {
let st = `<Hl>${text.substring(item[0], item[1] + 1)}</Hl>`
let rl = text.substring(item[0], item[1] + 1)
var temp = {
[rl]: st
}
all.push(temp)
return all
}, [])
for (let item in transformObj) {
let key = Object.keys(transformObj[item])[0]
let values = Object.values(transformObj[item])[0]
text = text.replace(key, values)
}
return text
}
var text = "This is a well-written paragraph of text."
var arr = [[5, 8], [23, 31]]
var result = transform(text,arr)
console.log(result)
Upvotes: 2