Georgi Kovachev
Georgi Kovachev

Reputation: 643

React-native style to text elements

I have defined JSX like this

<View style={[color: 'red']}>
<Text>Text1</Text>
<Text>Text2</Text>
<Text>Text3</Text>
</View>

View component doesn't have color property and it doesn't apply the text color settings of child elements.

I don't want to apply same style on individual elements. How can I define the style on the parent and apply to all child elements like normal in HTML?

Upvotes: 3

Views: 2887

Answers (3)

tlagreca
tlagreca

Reputation: 365

Other than applying a style to each element individually you could use something like the lodash _.map and render each child programatically and declare the style once.

Were you trying to do this because you wanted different colours on each of the text tags?

To make it less code you can "de-structure" it too.

const { aStyle, anotherStyle, andAnotherStyle } = styles;

Instead of the styles.aStyle. styles.anotherStyle....

Upvotes: 1

Bhullnatik
Bhullnatik

Reputation: 1312

The style is being propagated between Text components, so you could do something like:

<Text style={{color: 'red'}}>
  <Text>Text1</Text>
  <Text>Text2</Text>
  <Text>Text3</Text>
</Text>

Upvotes: 1

CoderLim
CoderLim

Reputation: 1232

As far as I know, there is no simple way to inherit style from super Componnet.

Maybe you can custom a component like this:

 class YourComponent extends Component {
  render() {
    let children = [];
    React.Children.forEach(this.props.children, (item, index) => {
      // textStyle is the style that you want children to inherit
      children.push(React.cloneElement(item, this.props.textStyle));
    });

    return (
      <View>
        { children }
      </View>
    );
  }
}

Upvotes: 1

Related Questions