Skip to content

Apply as many styles as you want in a single Text element simply by tagging parts of the string

Notifications You must be signed in to change notification settings

VincentQuillien/react-native-nested-text

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-native-nested-text

Apply as many styles as you want in a single Text element simply by tagging parts of the string.

Installation

npm install react-native-nested-text --save

Usage

Tag parts of the string you want to style: <{style|string}>. You can nest your tags like in any other markup language.

Then pass an object to Text nestedStyles prop with your react native styles as values and the names specified in the tags as keys.

import Text from 'react-native-nested-text';

const { blue, red, green } = stylesheet;
const styles = { r: red, g: green, b: blue };

<Text nestedStyles={styles}>
 {'Lorem <{b|ipsum <{r|dolor}> sit amet}>, consectetur <{g|adipiscing}> elit'}
</Text>

capture_react-native-nested-text

Like a simplistic markdown with only one tag and it takes the name of a React Native style object.

Motivation

React Native currently only allows a single style by Text element so you need to nest them to obtain the desired effect.

It breaks the flow of the text and it quickly becomes hard to read, especially when you have nesting several levels deep. If you are using internationalisation it will also significantly grow the number of entries in your translation files.

The same example as above in React Native vanilla :

// translation file
const latin = {
    loremIpsum: [
        "Lorem",
        " ipsum ",
        " dolor",
        " sit amet",
        ", consectur",
        " asipiscing",
        " elit",
    ]
}

// react component
const { blue, red, green } = stylesheet;

const LoremIpsum = () => (
  <Text>
    {loremIpsum[0]}
    <Text style={blue}>
      {loremIpsum[1]}
      <Text style={red}>{loremIpsum[2]}</Text>
      {loremIpsum[3]}
    </Text>
    {loremIpsum[4]}
    <Text style={green}>{loremIpsum[5]}</Text>
    {loremIpsum[6]}
  </Text>
);

About

Apply as many styles as you want in a single Text element simply by tagging parts of the string

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published