Conceptos básicos

Una breve introducción a glamorous

Motivation

There is no translation for this. Can you help translate it?

Why does glamorous exist?

The Problem

You like CSS in JS, but you don't like having to create entire component functions just for styling purposes. You don't want to give a name to something that's purely style-related. And it's just kind of annoying to do the style-creating, className assigning, and props-forwarding song and dance.

For example, this is what you have to do with raw glamor (or aphrodite or similar for that matter):

const styles = glamor.css({
  fontSize: 20,
  textAlign: 'center',
})
function MyStyledDiv({className = '', ...rest}) {
  return (
    <div
      className={`${styles} ${className}`}
      {...rest}
    />
  )
}

This Solution

With glamorous, that example above looks as simple as this:

const MyStyledDiv = glamorous.div({
  fontSize: 20,
  textAlign: 'center',
})

In fact, it's even better, because there are a bunch of features that make composing these components together really nice!

Oh, and what if you didn't care to give MyStyledDiv a name? If you just want a div that's styled using glamor? You can do that too:

const { Div } = glamorous

function App() {
  return (
    <Div
      fontSize={20}
      textAlign="center"
    >
      Hello world!
    </Div>
  )
}

Try this out in your browser here!

So that's the basics of this solution... Let's get to the details!

Instalación

Cualquier cosa

Este módulo se distribuye a través de npm que viene incluido con node y debe ser instalado como una de las dependencias de tu proyecto:

npm install --save glamorous

También depende de React y glamor por lo que también los necesitarás en tu proyecto (si no los tienes ya):

npm install --save react glamor

NOTA: Si estás utilizando React v15.5 o superior, también necesitarás tener prop-types instalado: npm install --save prop-types

Puedes utilizar uno de los siguientes formatos de módulos:

  • main: dist/glamorous.cjs.js - se exporta como un módulo CommonJS
  • global: dist/glamorous.umd.js y dist/glamorous.umd.min.js - se exporta como un módulo umd que es consumible en varios entornos, el más notable es como global.
  • jsnext:main y el módulo: dist/glamorous.es.js - se exporta usando la especificación de módulos ES, necesitará configurar webpack para hacer uso de este archivo, puedes hacerlo utilizando la propiedad resolve.mainFields.

El caso de uso más común es consumir este módulo a través de CommonJS:

const glamorous = require('glamorous')
const {ThemeProvider} = glamorous
// etc.

Si estás transpilando (y/o usando jsnext:main):

import glamorous, {ThemeProvider} from 'glamorous'

// también puedes importar Componentes Glamorous específicos (consulta la sección siguiente sobre los componentes "Incorporados")
import {Div, H2} from 'glamorous'

// las etiquetas con el mismo nombre que los objetos JavaScript incorporados son importables con un sufijo Tag
import {MapTag, ColorProfile} from 'glamorous'

Si deseas utilizar la opción global:

<!-- Agrega las dependencias -->
<script src="https://unpkg.com/react/dist/react.js"></script>
<script src="https://unpkg.com/prop-types/prop-types.js"></script>
<script src="https://unpkg.com/glamor/umd/index.js"></script>
<!-- Agrega la librería -->
<script src="https://unpkg.com/glamorous/dist/glamorous.umd.js"></script>
<script>
// Y usa window.glamorous aquí...
const glamorous = window.glamorous
const {ThemeProvider} = glamorous
</script>

Getting Started

There is no translation for this. Can you help translate it?

start using glamorous

Video Screenshot

Here is a basic example that shows you how to get started making component with css-in-js magic.

const { Div } = glamorous

function App() {
	return (
		<Div
			fontSize={20}
			textAlign="center"
		>
			Hello Glamorous!
		</Div>
	)
}

render(<App/>)
Hello Glamorous!

Conceptos básicos

Estilos dinámicos + Estilos estáticos

Una de las partes agradables de glamorous es que te permite hacer una clara separación entre sus estilos dinámicos y estáticos, forzándolo a elegir entre un objeto literal y una función. He aquí un ejemplo de tener ambos estilos dinámicos y estáticos:

const MyLink = glamorous.a(
  {
    color: 'blue',
    textDecoration: 'none',
  },
  ({size = 'small'}) => ({
    fontSize: size === 'big' ? 24 : 16,
  }),
  // puedes seguir proporcionando cualquier número de argumentos
  // y `glamor` los fusionará. En el caso de un
  // conflicto de estilos, el último gana.
)

Puedes ver una vista previa en vivo de este ejemplo en codesandbox.

Ten en cuenta, que también se pueden utilizar arrays de estilos si los necesitas:
const MyDiv = glamorous.div(
  [
    {
      [phoneMediaQuery]: {
        lineHeight: 1.2,
      },
    },
    {
      [phoneMediaQuery]: {
        lineHeight: 1.3, // esto ganará porque viene de último
      },
    },
  ],
  ({big, square}) => {
    const bigStyles = big ?
    {
      [phoneMediaQuery]: {
        fontSize: 20,
      },
    } :
      {}

    const squareStyles = square ?
    {
      [phoneMediaQuery]: {
        borderRadius: 0,
      },
    } :
    {
      [phoneMediaQuery]: {
        borderRadius: '50%',
      },
    }
    // Ten en cuenta que estamos devolviendo un array aquí
    return [bigStyles, squareStyles]
  },
)

// el resultado de <MyDiv big={true} square={false} /> será:
// @media (max-width: 640px) {
//   .css-1bzhvkr,
//   [data-css-1bzhvkr] {
//     line-height: 1.3;
//     font-size: 20px;
//     border-radius: 50%;
//   }
// }
//
// <div
//   class="css-1bzhvkr"
// />

Animación

Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas, y para cosas más avanzadas, puedes usar keyframes a través de la API css.keyframes de glamor.

// import * as glamor from 'glamor'

// Definimos los estilos de animación
const animationStyles = props => {
	const bounce = glamor.css.keyframes({
		'0%': { transform: `scale(1.01)` },
		'100%': { transform: `scale(0.99)` }
	})
	return {animation: `${bounce} 0.2s infinite ease-in-out alternate`}
}

// Definimos el elemento
const AnimatedDiv = glamorous.div(animationStyles)

render(
	<AnimatedDiv>
		Bounce.
	</AnimatedDiv>
)
Bounce.
CodeSandbox

glamorous-native

React Native

glamorous ofrece una versión para proyectos con React Native llamada glamorous-native.

npm install glamorous-native --save

Puedes aprender más acerca del proyecto glamorous-native.

Contribuidores

kentcdodds's GitHub avatar