theme.js - I have a Styled-Components theme which contains all of my app's color variations.
const colors = {
purples: {
60: '#AEA',
50: '#GSA',
},
blues: {
20: '#asd',
5: '#fasd',
}
...
I then have a UI component where I need to define an array of colors in a specific order:
import React from 'react';
const colors = ['#GSA', '#AEA', '#asd', '#fasd', '#AEA'];
I later use this colors
array to find the right color to use in my component based on state:
const getBackgroundColor = ({ currentPosition }) => {
const color = colors[(currentPosition) % colors.length];
return color;
};
This function is used within my styled-component like so:
const StyledCard = styled.div`
background: ${getBackgroundColor};
...
`;
The problem is my colors array is being set without the styled-components theme.
How can I define a const colors
using my theme when it is outside the styled element?
So I have done this in react-native and should be pretty similiar. I have a file called colors.js with all of the colors then I import them as an object so that was I can say colors[TheNameOfTheColorIWant]
colors.js
export const fadedPurple = '#9f91ad';
export const success = '#4fa579';
export const failure = '#ca374d';
Button Component
import * as colors from '../../../assets/styles/colors';
const Button = (props) => {
const {
onPress,
children,
color
} = props;
style = {
backgroundColor: colors[backgroundColor]
}
return (
<TouchableOpacity style={ style }
onPress={ onPress }
disabled={ disabled }>
{ children }
</TouchableOpacity>
)
Create a js file with this pattern:
'use strict';
var React = require('react-native');
var myStyle = React.StyleSheet.create({
red: {backgroundColor: 'red' },
blue: {backgroundColor: 'blue' }
)}
module.exports = myStyle;
your component js use require to use that style sheet
var customStyle = require('../the/path/to/commonStyleSheet');
Use now like this:
<View style = {customStyle .red} />
<View style = {customStyle .blue} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With