brigand / react-style-proptype

Validates style objects by ensuring the keys are valid css property names (in camelcase form).
MIT License
58 stars 11 forks source link

Support for arrays #2

Open marxsk opened 7 years ago

marxsk commented 7 years ago

It would be nice if module will support also arrays of styles e.g. [ myStyle, {width: 345}] which are pretty usual imho and are interpreted as a single style afterwards.

Currently, I'm using following format:

style: React.PropTypes.oneOfType([
  React.PropTypes.arrayOf(stylePropType),
  stylePropType
]).isRequired
brigand commented 7 years ago

Added in 1.3.0. Docs are in the readme. Thanks 😄

By the way, this doesn't seem to work on web, only react-native, or with specific custom components.

marxsk commented 7 years ago

I have to reopen this issue.

After adding the new version to my code, I have found out that it is not working as expected. Let assume that we have style={[mystyle, {width: 444}]}

before 1.3:

Warning: Failed prop type: Prop style passed to Foo. Has invalid keys 0, 1

with 1.3:

Warning: Failed prop type: Prop 0 passed to Foo isn't an object

So, the code correctly picked up a first item from the array but afterward it tests if it is object and it is not. Because it is a style, so it is represented by number.

brigand commented 7 years ago

I'm currently doing this, which should be the same, right?

module.exports.supportingArrays = React.PropTypes.oneOfType([
  React.PropTypes.arrayOf(module.exports),
  module.exports
]);

There's also a test that covers it, so I don't know what the issue is.

marxsk commented 7 years ago

I was able to track it down a bit, so I hope it will help.

With react-style-proptype@1.2.0 and my work-around it works without issues.

npm update react-style-proptype (=> installs 1.3.2)

Error message mentioned in my previous comment will occur even with my work-around. So there is some regression.

Prop foo isn't an object ...

foo is defined as:

const styles = StyleSheet.create({ ... foo: { height: 100, width: (WIDTH - RIGHT_BORDER), }, ... }

and foo is no longer an object with 1.3.2.

marxsk commented 7 years ago

So problem is in the src/index.js - commit 83482e2d912428d7550621edda19ad02599fbdad

if (typeof styles !== 'object') { throw new Error('Prop ' + propName + ' passed to ' + componentName + ' isn\'t an object'); }

There was no such check before.

brigand commented 7 years ago

Without that check it'll silently fail if a non-object is passed. I'll remove it, but I feel weird about it.

Published as 1.4.0.

marxsk commented 7 years ago

I understand but imho this check looks like React.PropTypes.object that does not work with styles and what is the reason why your module helps so much.

JPStrydom commented 1 year ago

I made react-native-style-prop-type which extends this library and adds React Native styles (like margenVertical, paddingHorizontal, etc.), array support, and some newer CSS properties (such as gap).