Reputation: 931
This is my component A:
const GenericTextInput = (props) => {
return (
<TextInput
style={styles.input}
{...props}
/>
);
};
This is my component B:
const SignIn = (props) => {
return (
<View>
<GenericTextInput
placeholder="Email"
autoFocus={true}
keyboardType="email-address"
returnKeyType="next"
autoCorrect={false}
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
/>
<GenericTextInput
placeholder="Password"
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
secureTextEntry={true}
/>
</View>
);
};
I want to add a specific styling to the 2nd GenericTextInput
in my component B. In the component A I want to use the spread operator
(it is so convenient).
If I simply make:
//component A
const GenericTextInput = (props) => {
return (
<TextInput
style={[styles.input, props.styles]}
{...props}
/>
);
};
//component B
const SignIn = (props) => {
return (
<View>
<GenericTextInput
placeholder="Email"
autoFocus={true}
keyboardType="email-address"
returnKeyType="next"
autoCorrect={false}
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
/>
<GenericTextInput
placeholder="Password"
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
secureTextEntry={true}
style={styles.customStyleForSecondInput}
/>
</View>
);
};
I'll have 2 style
props
in comp. A, and the second style
prop
will completely overwrite the first one.
What is the proper way of adding a specific styling to the 2nd GenericTextInput
?
Upvotes: 17
Views: 34432
Reputation: 8936
If you want your custom styles to completely overwrite the preset ones, I believe you can do something like
style={props.style || styles.input}
but I think you're asking how to have the custom styles overwrite some of the preset ones. In that case it would be
style={[styles.input, props.style]}
since you're passing the property down as 'style' not 'styles' you just drop the s at the end.
Upvotes: 5
Reputation: 35970
I usually destructure the named property (style
) out for the object, and use the rest operator to collect the remaining props into a new object:
const {style, ...rest} = props;
return (
<TextInput
style={[styles.input, style]}
{...rest}
/>
)
Note that this requires the transform-object-rest-spread Babel plugin. This plugin is included in the React Native Babel preset, so it will work out of the box -- but may not work in other JavaScript environments without this plugin.
Upvotes: 35