user3514137
user3514137

Reputation: 89

React Native: Dynamically print Text in multiple color

I'm trying to render a Text content on App by using React Native. The Text content is loaded from the server. Beside the content itself, the network response also tells me those words indexes which should be rendered in a different color.

For example:

// from the response JSON, I can tell:

contentString='How can we dynamic render text in multiple colors?'

index=[1, 3, 5]

I need to render the contentString in black on the App and render can(index 1), dynamic(index 3) and text(index 5) in yellow.

I did some researches on that and I noticed "Nested Text" would be a solution. Like:

<Text style={{color: 'black'}}>
  how
  <Text style={{color: 'yellow'}}>
    can
  </Text>
  we
  <Text style={{color: 'yellow'}}>
    dynamic
  </Text>

.......

</Text>

The index array differs from each request. I tried my best to write a function to support this DYNAMICALLY multi-color rendering, but with no luck. I'm still learning the algorithm and this function seems too challenging..

Can anyone throw some light on this? Much appreciates!

Upvotes: 0

Views: 1965

Answers (2)

ANKIT DETROJA
ANKIT DETROJA

Reputation: 2065

  • In Render create array of colors
  • random function for get random number every time
  • you pass the random number in backColor array. index of the colors array
render() {

var backColor = ["#c36a2d", "#afa939", "#60204b", "#ca3e47", "#f7b71d", "#f36886", "#614ad3", "#0c99c1", "#4e3440", "#010059"];
const rand = Math.floor(Math.random() * 9) + 1;

    return (
       <Text style={{color: 'black'}}>
         {contentString.split(" ").map((x, ind) => 
             <Text style={{color: backColor[rand]}}>
              {x+ " "}
             </Text>)
          }
      </Text>
   )
}

Upvotes: 0

Sateesh Pagolu
Sateesh Pagolu

Reputation: 9606

You could do something like this..

 <Text style={{color: 'black'}}>
     {contentString.split(" ").map((x, ind) => 
           <Text style={{color: index.includes(ind)?'black':'yellow'}}>
            {x+ " "}
           </Text>)
      }
 </Text>

Live Demo Here

Upvotes: 1

Related Questions