Styled Components for React Native the way they should have been.

Last update: Apr 1, 2022

GitHub license Npm package total downloads GitHub forks GitHub stars

TypeScript

💄 Styled-RN

Styled Components for React Native the way they should have been.

Inspired by this article


Intro

Why 💄 styled-rn it better than 💅🏼 styled-components/native ?

Well, first of all, using styled components should be fun, but using css to style a React Native app is cumbersome and often ends up to be very messy.

Also:

  • styled-rn gives you access to ALL React Native style props
  • styled-rn is faster because it does not do tedious string template processing
  • styled-rn is easier to use (again, no messy string templates)
  • styled-rn is fully typed and has a nice API
  • styled-rn supports custom props, theme via ThemeProvider, multiple style objects and more..
  • styled-rn has a shorter name ;)

Usage:

npm i styled-rn
import { styled } from "styled-rn";

// Basic usage
export const Container = styled.View({
  flexDirection: "row",
  backgroundColor: "cyan",
});

// Use with any component
export const CoolAndBoldComponent = styled(CoolComponent, {
  fontWeight: "bold",
});

// Pass props to the styled component (attrs)
export const NonWrappingText = styled.Text({
  color: "blue",
}, {
  attrs: {
    numberOfLines: 1,
    ellipsizeMode: 'tail',
  }
});

Theming:

You will need to do a few things in order to propagate the theme prop into all of your styled components:

  1. Define your theme object and the type for it
  2. Augment the Theme type
  3. Wrap your app in ThemeProvider

First, define your theme:

// mytheme.ts

export const theme = {
    primary: "blue",
    background: "white",
    ...
} as const;

export type MyAppTheme = typeof theme;

TODO: add example on how to use multiple themes

Now you need to augment the default Theme type with your own type. In order to do that, create a definitions file at the root of your source tree (e.g. global.d.ts) and add the following to it:

import { MyAppTheme } from './mytheme.ts'

declare module 'styled-rn' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  interface Theme extends MyAppTheme {}
}

And finally, the wrapping, as usual:

// App.tsx

import { ThemeProvider } from 'styled-rn';
import { theme } from './mytheme.ts';

export default function App() {
    return (
        <ThemeProvider theme={theme}>
            { /* your app components */}
        </ThemeProvider>
    )
}

And that's it! You can now access your theme in any styled component:

export const Button = styled.TouchableOpacity(
  ({ theme }) => ({
    backgroundColor: theme.background,
  })
);

If you want to use custom props in your styled component, make sure that your custom props interface extends ThemedProps. E.g.

// Important:         👇
interface ButtonProps extends ThemedProps {
  disabled?: boolean;
}

export const Button = styled.TouchableOpacity(
  ({ disabled, theme }: ButtonProps) => ({
    opacity: disabled ? 0.3 : 1,
    backgroundColor: theme.background,
  })
);

// Using conditional styles with custom props
interface SmartComponentProps extends ThemedProps {
  active?: boolean;
}
export const SmartComponent = styled.TouchableOpacity(
  ({ active, theme }: SmartComponentProps) => [
    {
      fontSize: 16,
    },
    active && {
      fontWeight: theme.activeFontWeight,
      color: theme.activeColor,
    },
  ]
);

You can also use theme in your components by calling the useTheme() hook or by wrapping your component with withTheme() HOC.

import { useTheme } from 'styled-rn';

export const MyComponent = () => {
    const theme = useTheme();
}

Known Issues

  • When component returns the style from inline function sometimes the style object has to be type casted to ViewStyle, TextStyle, etc... Otherwise, you'll get a weird TS error. It looks like a TS bug. If you don't want to cast your styles, make sure that you pass props to the function and USE THE PROPS in your styles.

Contributing

Issues and Pull Requests are always welcome.

GitHub

https://github.com/velsa/styled-rn
You might also like...

Flexibly styled chat-widget for your react apps.

Flexibly styled chat-widget for your react apps.

Flexibly styled chat-widget for your react apps. It was mainly created for integration with chat-bots in messengers.

Jun 11, 2021

A styled switch for React built using Emotion CSS and Framer motion

A styled switch for React built using Emotion CSS and Framer motion

A styled switch for React built using Emotion CSS and Framer motion

Aug 27, 2021

A terminal style/styled portfolio website made with 3 using react.

A Terminal Styled Portfolio Website. 🐱‍💻, a terminal style/styled portfolio website made with 3 using react.

May 14, 2022

Seamless mapping of class names to CSS modules inside of React components.

Seamless mapping of class names to CSS modules inside of React components.

React CSS Modules React CSS Modules implement automatic mapping of CSS modules. Every CSS class is assigned a local-scoped identifier with a global un

May 7, 2022

Style your React components with simplicity using css inside your comments.

Style your React components with simplicity using css inside your comments.

Oct 12, 2021

Vite plugin that emulates Scoped CSS for React components

vite-react-css Vite plugin that emulates Scoped CSS for React components (using generated class names) Compatible with SSR Automatic code-splitting Ho

Feb 7, 2022

Encapsulated styling for your javascript components with all the power of javascript and CSS combined.

Stilr Encapsulated styling for your javascript components with all the power of javascript and CSS combined. Unique class names (Content Hash Based) U

May 7, 2021

Incredible fast template toolkit for making new or re-styling existing components with Tailwind CSS.

Stail Incredible fast template toolkit for making new or re-styling existing components with Tailwind CSS. Why it's needed? First of all, I'm tired fr

Jan 25, 2022

Material-tailwind - An easy-to-use components library for Tailwind CSS and Material Design

Material-tailwind - An easy-to-use components library for Tailwind CSS and Material Design

Material-tailwind - An easy-to-use components library for Tailwind CSS and Material Design

May 10, 2022
Comments
  • 1. Theme example

    I wondered if the multi-theme example got made TODO because of the issue with as const and having a literal type object. There's many possible answers to ensure your types match, but here's the one I use (because I keep Widen around for other uses). The docs for it are here

    export const mainTheme = {
      primary: "blue",
      background: "white",
    } as const
    
    export const darkTheme: GeneralTheme = {
      primary: "white",
      backgrund: "black",
    }
    
    export type AppTheme = typeof mainTheme
    export type GeneralTheme = Widen<typeof mainTheme>
    
    
    type Widen<T> = { [key in keyof T]: ToPrimitive<T[key]> }
    
    type ToPrimitive<T> = T extends string
      ? string
      : T extends number
      ? number
      : T extends boolean
      ? boolean
      : T extends (..._args: any[]) => any
      ? (..._args: Parameters<T>) => ReturnType<T>
      : T
    
    
    Reviewed by orta at 2022-02-23 09:00
Typograpy components for react and styled-components
Typograpy components for react and styled-components

styled-typography Typograpy components for react and styled-components styled-typography is a small set of components, using styled-components, to bet

May 1, 2022
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

Feb 27, 2022
Imersão React.js 3º edição. Project using ReactJS, Next JS, and Styled Components for the week challenge by Alura. We created a social network inspired by Orkut.

Example app with styled-components This example features how you use a different styling solution than styled-jsx that also supports universal styles.

Jul 19, 2021
Minimal and performant React component library built on styled-components

Minimal and performant React component library built on styled-components

Jan 3, 2022
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components

Simple Styled Form Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utiliza

Oct 29, 2021
The simplest solution for content loading in React and styled-components.

styled-content-loader The simplest solution for content loading in React and styled-components. Getting Started npm install styled-components styled-c

Jul 13, 2021
Simple Portfolio Using React Hooks & Styled Components
Simple Portfolio Using React Hooks & Styled Components

Said MOUNAIM To view a live example, click here. Getting Started These instructi

Mar 20, 2022
🎥A criação de uma UI para Streaming utilizando React.js, Styled Components junto com Sass.
🎥A criação de uma UI para Streaming utilizando React.js, Styled Components junto com Sass.

Movie Screen - Exercitando React, Styled Components e Sass ??️ Dependencias React Styled Components Sass React Icons ?? Objetivo O principal intuito d

Dec 28, 2021
🔧 💅 Jest utilities for Styled Components

Jest Styled Components A set of utilities for testing Styled Components with Jest. This package improves the snapshot testing experience and provides

May 10, 2022
Front-End Mentor: Landing page usando ReactJS + Styled Components
Front-End Mentor: Landing page usando ReactJS + Styled Components

Front-End Mentor: Fylo Landing Page ✨ O projeto se trata de um desafio disponível no site Front-End Mentor. A ideia é desenvolver um código que se apr

Feb 14, 2022