Home > Back-end >  Why doesn't this style property assignment work as expected in React Native?
Why doesn't this style property assignment work as expected in React Native?

Time:10-30

I've tested the below code on React Native in my browser (using Expo CLI Webpack) and the result is three green squares down the left side of the screen.

import React, { useState } from "react";
import { View, TouchableOpacity, Text, StyleSheet } from "react-native";

const styles = {
  width: 100,
  height: 100,
  backgroundColor: "green"
};

const Rectangle = (label, value) => {
  return (
  <View style={[styles, {[label]: value}]}/> // Line I expect to modify style.backgroundColor
  );
};

const Page = () => {
  return (
    <View style={{flex: 1, justifyContent: "space-evenly"}}>
    <Rectangle label="backgroundColor" value="red" />
    <Rectangle label="backgroundColor" value="green" />
    <Rectangle label="backgroundColor" value="blue" />
    </View>
  );
};

export default Page;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

However, I expected to see a red, green and blue square. I've tried to mimic a pattern used several times on this page of the RN documentation but it isn't behaving as I expected. Could someone please explain what I've misunderstood here? Thanks.

CodePudding user response:

Props will be passed as a single object attribute, not as multiple attributes.

Simply replace (label, value) with ({label, value}).

By putting curly braces around your props you're destructing the first attribute, which in this case is your props.

CodePudding user response:

There are two issues with your code.

First, as Ugur Eren mentioned, you are not destructuring your props.

Second, you are putting your styles objects into an array.

const Rectangle = ({label, value}) => { //<-- use destructuring. See Ugur Eren answer
  return (
  <View style={{...styles, [label]: value}}/> //<-- use an object. Use spread syntax to stack values
  );
};

Using Spread Syntax allows you to build a new object, stacking values that are passed in (or build a new array, appending values that are passed in).

It looks like this is already what you are trying to do, except you were using an array (which won't overwrite/stack values) and missing the spread syntax operator (...).

Edit: array syntax correct

Looks like I'm wrong about this -- the Array syntax for style is correct. It is used in the official React Native documentation on style:

        <Text style={[styles.bigBlue, styles.red]}>bigBlue, then red</Text>

Weirdly, there is no mention of this in the React documentation on style, neither on the DOM elements page nor in the FAQ on styling, which only mention using Objects to pass style.

  • Related