In React Native, you can create dynamic styles using functions that return style objects. This allows you to change the styles of your components based on certain conditions.
Here's an example:
import { StyleSheet } from 'react-native'
import { Color } from 'theme/theme'
import { StyleSheetType, StylesFunctionProps } from 'components/MyComponent/types'
export const styles: StylesFunctionProps = ({ isDisabled, focused }) =>
StyleSheet.create<StyleSheetType>({
primary: {
backgroundColor: isDisabled ? Color.Gray : Color.Primary,
borderColor: isDisabled ? Color.Gray : Color.Primary,
},
secondary: {
backgroundColor: 'transparent',
borderColor: isDisabled ? Color.Red : Color.Secondary,
},
// ... rest of the styles
})
Note: StyleSheetType must contain all the StyleSheet styles object keys such as:
type StyleSheetType = {
primary: ViewStyle
secondary: ViewStyle
anotherStyle: TextStyle
// ... rest of the styles keys
}
StylesProps are props you want to pass to the StyleSheet
export type StylesProps = {
isLoading?: boolean
isDisabled?: boolean
/// ... rest
}
Also StyleFunctionProps is:
export type StylesFunctionProps = (props: StylesProps) => StyleSheetType
Usage:
import styles from './styles';
const MyComponent = () = >{
const isLoading = /* some condition */;
const isDisabled = /* some condition */;
const dynamicStyles = styles({ isDisabled, isLoading });
return (
<View style={dynamicStyles.primary}>
{/* rest of the component */}
</View>
);
}