Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when creating new object from existing one using `...`: In this environment the sources for assign MUST be an object

In my React Native app, I have a situation where one particular child of a component that I render should receive either a green or red borderColor.

Now, I don't want to create two separate entries in my styles for these two situations since they only differ in the borderColor property.

My idea was to derive the proper style object from the ones which I have in my styles like so:

const styles = StyleSheet.create({
  amountSection: {
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row',
    borderRadius: 3
  }
})

render() {
  const amountBorderColor = this.state.isClaim ? 'green' : 'red'
  const amountStyles = {
    ...styles.amountSection,
    borderColor: amountBorderColor
  }

  return (
    // ... apply amountStyles at appropriate component
  )
}

However, this code gives the following error:

Unhandled JS Exception: In this environment the sources for assign MUST be an object.This error is a performance optimization and not spec compliant.

Apparently the error is hit on the line where I define amountStyles. Anyone knows why this happens? Is there something wrong with my syntax? I am using the ... notation to create a new object from an existing one and add some additional properties to it.

like image 970
nburk Avatar asked May 04 '16 06:05

nburk


Video Answer


2 Answers

As @PitaJ pointed out, my issue was that StyleSheet.create doesn't return a plain javascript object, so the ... operator can't be applied.

I only want to add a solution to my original problem as well, that was to derive two different style objects from one basic one where only one property is added.

The docs for the StyleSheet API indicate that the method flatten can be used for this:

const amountBorderColor = this.state.isClaim ? 'green' : 'red'
const amountStyles = StyleSheet.flatten([styles.amountSection, {borderColor: amountBorderColor}])
like image 59
nburk Avatar answered Oct 19 '22 15:10

nburk


It appears that the factory function does not return a JavaScript Object with the property that you need, and that the environment does not want to apply the spread operator to an undefined value. If you want to use it, pull out the object you pass to that function into a different variable.

like image 6
PitaJ Avatar answered Oct 19 '22 16:10

PitaJ