24

I want to render a single line of text with some words highlighted in a different color.

I would ideally do it with a span tag with react.

Wondering how would i do the same with react-native?

3 Answers 3

60

You can achieve this by using nested Text components

<Text style={{color: 'blue'}}>
    I am blue
    <Text style={{color: 'red'}}>
        i am red
    </Text>
    and i am blue again
</Text>

Here's a link to the documentation explaining it better

3
  • What if you have dynamic text? Imagine text is from server with some placeholders to signify that the client should highlight. Mar 31, 2015 at 18:56
  • That's quite specific, so it's not provided by default. It shouldn't be that hard to accomplish though. Try writing a specific function that parses the string from the server and outputs an object that contains the styles to apply to each substring. Then you can feed this object to a custom component that renders nested Text components like the one above.
    – mttcrsp
    Mar 31, 2015 at 19:56
  • Ya. That makes sense. Mar 31, 2015 at 20:03
3

Simply nest <Text> elements

<Text>
    I am some text with 
    <Text style={{fontWeight: 'bold'}}>bold</Text> 
    stuff
<Text>
2

You can do it better, my way:

CText = (props) => <Text style={{color: props.color}}>{props.children}</Text>

inside render add:

const CText = this.CText

and return

<Text>I am <CText color={'red'}>Blue color</CText> and <CText color={'blue'}>Blue color</CText></Text>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.