Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With a Styled-Components, how to set an array of colors outside of the Styled Component?

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?

like image 736
AnApprentice Avatar asked Jun 23 '18 15:06

AnApprentice


2 Answers

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>
  )
like image 95
Tall Paul Avatar answered Oct 30 '22 08:10

Tall Paul


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} />
like image 20
Pramod Avatar answered Oct 30 '22 10:10

Pramod