How to use JS object variables for colors in CSS

Asked

Viewed 1,750 times

0

if I have an object JS for ex:

cores = {
 main: "#333",
 institutional: "blue"
}

and I use styled components to build my styles css so I create him like this:

styled.View`
  background-color: cores.main;
`;

it does not work because colors.main = "#333" and not #333 quotation marks I think it’s in the way of someone who knows what to do?

  • You couldn’t do it var cor = "#333" and then in colors you put cores = { main: cor } ? It’s just an idea even because I don’t know much about JS, but it will pass :)

2 answers

3


First of all it would be ideal if you put this variable object as a theme in Provider of styled-components, thus:

import { ThemeProvider } from 'styled-components';

const cores = {
 main: "#333",
 institutional: "blue"
};

function App() {
  return (
    <ThemeProvider theme={cores}>
      <Componente />
    </ThemeProvider>
  );
}

This allows you to use the theme variables on all components without having to import the object, aside from the fact that changes in the Preview are reflected everywhere by the app.

And then, in the export do Component, you do so, for example:

import styled from 'styled-components'
import { View } from 'react-native'

export default styled(View)`
  background-color: ${props => props.theme.main};
`;

It works. I think it kind of Overkill use styled-components in React Native apps, but this is a topic for another discussion...

  • Pretty cool, didn’t know that! about Overkill I think the same about TS

1

Here’s an example of how to do this

The archive with the colors:

export default {
  white: "#fff",
  lighter: "#eee",
  light: "#ddd",
  regular: "#999",
  dark: "#666",
  darker: "#333",
  black: "#000",

  primary: "#e5556e",
  secondary: "#444a5a",
  sucess: "#00bfa5",
  danger: "#e37a7a",
  background: "#27202c",

  transparent: "transparent",
  darkTransparent: "rgba(0, 0, 0, 0.6)",
  lighterWhiteTransparent: "rgba(255, 255, 255, 0.2)",
  whiteTransparent: "rgba(255, 255, 255, 0.5)",
  darkerWhiteTransparent: "rgba(255, 255, 255, 0.8)"
};

The file with Styled Components, where the color file is imported:

import styled from "styled-components/native";
import { Dimensions } from "react-native";
import { colors } from "../../styles";
var screen_height = Dimensions.get("window").height;

export const Container = styled.View`
  flex: 1;
  justify-content: center;
  align-items: center;
  padding: 30px;
  height: ${screen_height};
  background-color: ${colors.background};
`;

export const Logo = styled.Text`
  color: ${colors.primary};
  font-size: 48px;
  font-weight: 500;
`;

export const Screen = styled.View`
  flex: 1;
`;

export const Form = styled.View`
  width: 100%;
  margin-top: 30px;
`;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.