Swiler
Swiler

Reputation: 29

React Native pass more props to style

I'm trying to make the component more flexible but I can't find a way to pass more properties to the style I thought this would work but nothing, ... morestyles is for my container.

    import React from "react";
    import { StyleSheet, View, Text } from "react-native";
    
    // component
    import Radio from "../components/Radio";
    
    function RadioText({ color, title, ...**moreStyles** }) {
      return (
        <View style={[styles.container, { ...**moreStyles** }]}>
          <Radio color={color} />
          <Text style={styles.text}>{title}</Text>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flexDirection: "row",
      },
      text: {
        fontSize: 11,
      },
    });
    
    export default RadioText;

Upvotes: 0

Views: 40

Answers (2)

Sam
Sam

Reputation: 2351

Would something like this work?

<View style={{...styles.container, ...moreStyles}}>

Or maybe a loop like

let style = styles.container
moreStyles.forEach((s) => {
    style = {...style, ...s}
})

Here's an article which describes mergin JSON objects, which is what the styles would be

Upvotes: 0

GitGitBoom
GitGitBoom

Reputation: 1912

It looks like your spreading the styles in props.

Change to:

function RadioText({ color, title, moreStyles }) {
      return (
        <View style={[styles.container, moreStyles]}>
          <Radio color={color} />
          <Text style={styles.text}>{title}</Text>
        </View>
      );
}

Then usage would be:

<RadioText title="foo" color="red" moreStyles={{padding: 20}} />

If you want to continue to use the rest operator as you have in your question you'll have to pass each style prop like:

<RadioText title="foo" color="red" padding={20} />

Either way there is not reason to clone the moreStyles prop.

Upvotes: 2

Related Questions