Search code examples
arraysreact-nativestyles

React Native mapped array objects inside style array?


Been trying to work this out for a couple hours now and no dice. Everything works except the style array. Not sure how to include the mapped array objects in the style array?

Error: Failed prop type: Invalid props.style...

So the <Text Style={ array format is incorrect but I don't know the correct syntax to convert it. Any help greatly appreciated.

const navTabs = [ {label: 'Home'}, {label: 'Next'} ]
const { Home, Next } = styles

{navTabs.map(x => 
<TouchableOpacity key={x.label} onPress={ () => navigate(`${x.label}`)}> 
<Text style={ [ navTxt, `${x.label}` ] }> {x.label} </Text> 
</TouchableOpacity> )}

const styles = { navTxt:{backgroundColor:'#000', paddingHorizontal: 5}, Home:{color: 'red'}, Next:{color: 'white'} }

Solution

  • to be honest it looks odd for me, but I think this is what you want to achieve

    Update: there's a workaround you can do, as following

    render() {
    const navTabs = [
      { label: 'Home' },
      { label: 'Next' },
    ];
    const styles = {
      Home: {
        color: 'rgb(255, 0, 0)',
      },
      Next: {
        color: 'rgb(0, 0, 0)',
      },
      navTxt: {
        backgroundColor: 'rgb(0, 255, 0)',
      },
    };
    
    return (
         {navTabs.map(x =>
              <TouchableOpacity key={x.label} onPress={() => {}}>
                <Text style={{ ...styles.navTxt, ...styles[x.label] }}> {x.label} </Text>
              </TouchableOpacity>
            )}
    );
    }