Reputation: 608
I just recently started using React Native and trying my best to be a good little developer I'm defining the propTypes
for my components. However there is one thing that irks me about this process, which is the style
prop type doesn't seem to be "composable" in any way.
For example, I want to create a Divider
component that essentially consists of a View
with a flat backgroundColor
and a width
/height
set to the value of a thickness
property; depending upon it's orientation.
When defining the propTypes
for the Divider
component I use the View.propTypes
as I've seen people on the internet recommend, only I would like to use color
instead of backgroundColor
to specify the color of the divider. View.propTypes.style
doesn't have a color
property, and it doesn't seem possible to extend/compose the built-in style
prop type.
Has anyone run into similar problems and have a decent remedy/workaround?
Another slightly different but related example: lets say I want to develop a TextField
component which wraps TextInput
and provides all of it's styling options plus an icon
prop which will render the specified icon "inside" and to the left of the TextField
the JSX might look something like this:
render() {
const {
icon,
style, // how to efficiently spread this across View and TextInput?
...props
} = this.props;
return (
<View style={styles.container}>
{icon()}
<TextInput ... />
</View>
);
}
I would like the spread the style
supplied across the View
and TextInput
components where relevant (e.g. the backgroundColor
property should be applied to the View
component not the TextInput
, likewise the color property should be applied to the TextInput
component).
Upvotes: 0
Views: 837
Reputation: 7474
Because you have a custom component, I don't think it is a good idea to have things mixed. My suggestions:
(1) if you really want someone to be able to pass in "style" as written, choose one and only one component where that style prop will spread to (e.g. choose the View and make it clear it should only be style props relevant to a view). Then, you could accept another custom prop that would define the style for the TextInput:
<View {...props.style} />
<TextInput {...props.textInputStyle} />
{/* ... */}
(2) Define custom props one by one on your component that will modify its style. For e.g. <YourComponent color="white" backgroundColor="red" />
would mean you would use props.color
to define the text component's color and props.backgroundColor
would take care of the view component's background:
<View style={{ backgroundColor: props.backgroundColor, ... }} />
<Text style={{ color: props.color, ... }} />
{/* ... */}
Remember that it is your custom component and you can accept any props, with any name! The implementation is up to you; internally, you should follow the basic component prop names -- but from without, your own custom component can be used in any way you'd like!
Upvotes: 2