GithubHelp home page GithubHelp logo

rootstrap / react-native-use-styles Goto Github PK

View Code? Open in Web Editor NEW
65.0 4.0 17.0 320 KB

A classy approach to manage your react native styles.

License: MIT License

JavaScript 100.00%
react-native styles usestyles hooks classes

react-native-use-styles's Introduction

npm version

A classy approach

Did you ever want to organize your styles properly? This library contains an easy to use API that lets you do it in a classy way.

Installation

npm i react-native-use-styles

Usage

Using styles

import useStyles from './my-namespaced-styles';

const Component = ()  {
  const s = useStyles();

  return (
    <Text styles={s`.global .namespaced`}>
      Hello World!
    </Text>
  );
}

Note that we are classy now, and nobody would deny it. Next we'll define our .global and .namespaced styles to use them in our components as we are doing in this example.

Global styles

global-styles.js

import { GlobalStyles } from 'react-native-use-styles';

GlobalStyles({
  global: 'flex:1 fx:dir:row',
});

We are using aliases or shortcuts to define our styles. This is equivalent to do:

import { GlobalStyles } from 'react-native-use-styles';

GlobalStyles({
  global: {
    flex: 1,
    flexDirection: 'row',
  },
});

Namespaced styles

my-namespaced-styles.js

import { Styles } from 'react-native-use-styles';

export default Styles({
  reused: 'bg:color:green',
  namespaced: '.global .reused color:purple',
});

Namespaced styles are a way to isolate a group of styles for a particular part of your app, it could be styles for a component, a screen, etc. This is a way to group semantically and avoid collisions between your styles. Note that we are exporting the result of our namespaced definition.

Constants

import { GlobalStyles } from 'react-native-use-styles';

GlobalStyles({
  constants: {
    purple: 'purple',
  },
  path: 'color:$purple',
  object: { color: '$purple' },
});

You can define constants in your global or namespaced styles that will be available to reuse with the $ prefix.

Computed and Dynamic styles

Computed styles:

import useStyles from './my-namespaced-styles';

const Component = ()  {
  const isPurple = useState(true);
  const s = useStyles([isPurple]);

  return (
    <Text styles={s`fx:1 &purple`}>
      Hello World!
    </Text>
  );
}

Computed styles are prefixed with the & character. Note that we are passing isPurple as a hook's dependency to track it changes. We can then use this dependency in our computed styles as following.

import { Styles } from 'react-native-use-styles';

export default Styles({
  computed: {
    purple: ([isPurple]) => ({ color: isPurple ? 'purple' : 'black' });
  }
});

If the dependencies change, only styles with a computed in it will be recomputed.

Dynamic styles:

import useStyles from './my-namespaced-styles';

const Component = ()  {
  const isPurple = useState(true);
  const s = useStyles();

  return (
    <Text styles={s`fx:1 ${isPurple && '.purple'}`}>
      Hello World!
    </Text>
  );
}

And a simple style definition as following:

import { Styles } from 'react-native-use-styles';

export default Styles({
  purple: { color: 'purple' },
});

There are plenty more things you can do with useStyles, learn more in User Guide

Definition order

You want your global styles to be defined or imported before all the other styles. So just import your global styles at the top of your App.js or your main entry point; before the imports of your custom or navigation component.

App.js

import './globalStyles'; // ultra safe zone
import React from 'react';

import CustomComponent from './CustomComponent';

export default function App() {
  return <CustomComponent />;
}

List of aliases

This is the current list of aliases available, we plan to add more.

bot = bottom;
col = column;
dir = direction;
fx = flex;
lt = left;
rt = right;
bg = background;
txt = text;
jf = justify;
pd = padding;
wd = width;
hg = height;

Performance

This library was created with performance in mind; useStyles has multiple cache layers to avoid unnecessary renders, calculations, and transformations. More info in the User Guide

Contributing

We plan to keep working in the library to optimize and add new features (contributions are welcome). If you have an idea that could make this library better we would love to hear it. Please take a look at our Contributing Guidelines to get to know the rules and how to get started with your contribution.

How to run the demo app

In order to contribute with some code you will need to test your changes within the demo app. At the moment the mechanism that we are using to test the lib inside the app is to import it locally. That means that:

You need to install the dependencies on the library in production mode (npm install --only=prod) so you don't have problems with dual installations of react-native each time you make a change, you need to do a force install of the library inside the demo folder. If the problem persists, after you test or build the app you encounter duplicated issues, you may want to delete the modules of one of the packages, the lib or the demo app, to solve this issue.

If you are comfortable using something like Wix's wml, it could provide a better development experience for you. We wanted the main contributing option to not require any extra installations or knowledge. Symlinks have not worked and that is why we recommend Wml.

License

react-native-use-styles is available under the MIT license. See the LICENSE file for more info.

Credits

react-native-use-styles is maintained by Rootstrap with the help of our contributors.

react-native-use-styles's People

Contributors

agustito37 avatar gajanangitte avatar k-guy-dev avatar lmajhi avatar lrnz09 avatar mato2593 avatar princefishthrower avatar vfreitas- avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-use-styles's Issues

Feature: constants in object styles

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

Given that currently, we can use constants but not for object styles; It would be great having the possibility of using constants when defining object styles too.

What we can do right now:

GlobalStyles({
  constants: {
    red: '#ff0000'
  },
  global: 'color:$red'
});

What we should have too:

GlobalStyles({
  constants: {
    red: '#ff0000'
  },
  global: {
    color: '$red'
  }
});

Not sure how this is going to impact on the performance, given we need to check if there's a constant in every object's property value, maybe we should create a draft for this.

Typescript types declaration file

Bugs and Questions

Checklist

  • This is a @rootstrap/react-native-use-styles specific issue.

  • I am using the latest version of @rootstrap/react-native-use-styles

  • I've searched open issues to make sure I'm not opening a duplicate issue

The Problem

It would be great to have typescript types to avoid the warning about not having them Could not find a declaration file for module ....

Typings are missing in latest release 1.3.0

Bugs and Questions

Checklist

  • This is a @rootstrap/react-native-use-styles specific issue.

  • I am using the latest version of @rootstrap/react-native-use-styles

  • I've searched open issues to make sure I'm not opening a duplicate issue

The Problem

I just installed version 1.3.0 and it seems it's missing the typings that were added with #11.

Reproduction

Install version 1.3.0 and check the node_modules.

Feature: CSS notation

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

It would be great to have the possibility of writing styles with a CSS notation, something similar as you can do in emotion maybe (?).

This doesn't seem something tough to create, given there are a couple of libraries that make the CSS to JS-Styles transformation; the only blockers are the custom fields that need to be treated differently: constants and computed.

Feature: Media queries, conditional based styles or size normalizer

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

It could be great to have some kind of conditional based styles feature, like media queries. Something as this: https://github.com/vitalets/react-native-extended-stylesheet#media-queries. Maybe is not worth; but it could be a good feature.

export default Styles({
  queries: {
    "ios": {
       ...
     },
     "android": {
      ...
    },
    "max-width: 329": {
      ...
    }
  }
})

As an alternative, we can go for a size normalizer as https://github.com/nirsky/react-native-size-matters; where you can put the sizes with a notation like 100@vs to normalize the size depending on the device specifications.

Warnings code

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

Improve warnings code. Today we have a repetitive code to add a development warning; e.g:

if (process.env.NODE_ENV !== "production" && someCondition) {
    console.warn(
        `useStyles [warningKey]: "[description]. You are seeing this warning because you are in development mode. In a production build there will be no warning.`
    );
}

It would be great to have this logic encapsulated into a function as this:

warn(someCondition, description, warningKey);

It's important that these warns don't appear in the production build. For that we are using @rollup/plugin-replace, so we need to change its configuration in order to support this.

Improve errors: invalid-path

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

As a developer, I want to have descriptive errors when the library fails.

Error:

invalid-path: when you are trying to use an invalid path.

Example:

const s = useStyles();

return <Text styles={s`invalid-path`} />

If the path is invalid given we are not receiving what we expect, that is a key-value path key:value, a class.myClass, or a namespace @namespace.class we should raise an error.

Documentation: Benchmark

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

I had made some performance tests and all seems to be working as expected, but It would be great to have some kind of benchmarking (when using this library in a large project with lots of styles defined) in the README.md or USER_GUIDE.md.

Contributions are welcome

Contributions are welcome

This is a new library; so, if you come up with a cool feature to add to this library, just create an issue and we can discuss it.

Thanks!

Improve errors: non-existent-namespace

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

As a user, I want to have descriptive errors when the library fails.

Errors:

Non-existent-namespace: when you are trying to use a namespace that doesn't exist.

Example:

const s = useGlobalStyles('non existent namespace here');
const styles = globalUse('non existent namespace here');

These should raise an error only on development.

Feature: Add Components with styles attribute

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

It would be awesome having custom components that internally uses the useStyles hook. This is a proof of concept, we need a draft for this.

import namespace from './my-namespaced-styles';
const { Text } = namespace;

const component = () ⇒ {
  return (
    <Text styles=".global-style .local-style ">
      Hello World!
    </Text>
  );
}

In this case, the custom Text component is a wrapper of the React Native's Text component and this wrap is using the library to transform the styles prop to its respective styles.

Pre-commit or pre-push hook

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

We should run a linter and the tests before pushing it to the repository. Having a pre-commit or pre-push hook would be great.

Improve USER_GUIDE.md

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

The USER_GUIDE.md is pretty lame, we can improve it. This probably involves changes in the README.md.

React test renderer config

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

It would be great having tests with react-test-renderer. We should add the necessary configuration for them, and maybe an example test using the renderer. Maybe we can use react-native-testing-library (?)

Integration with styled-components

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

We would like to use react-native-use-styles with styled-components. Because styled-components is not supporting global styles with react-native, what could be fixed with react-native-use-styles. Would it be possible to seed styles from react-native-use-styles in a styled-components string template?

Return a merged style object instead of an array

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

This is a small change, today the hook is returning an array of styles, it should be more usable to return just a merged object of the styles inside these array of styles.

The purpose of this change is to be able to do this:

<Component style={[s`.global .namespaced`, { color: red }]} />

Instead of doing this:

<Component style={[...(s`.global .namespaced`), { color: red }]} />

It should be a small change when returning styles inside this function:

export const GlobalUse = (path, namespace) => {

This is going to break the tests given they are expecting an array, not an object, but the solution should be trivial.

Add object styles inheritance.

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

Add object styles inheritance. Something like this:

{
  style1: {
    fontSize: 12,
  },
  style2: {
    color: 'red',
  },
  style3: {
    extends: '.style1 .style2'
    textAlign: 'center',
  }
}

Improve errors: computed style outside computed property

Feature Requests

Checklist

  • My feature request is specific to @rootstrap/react-native-use-styles.

  • I've searched open issues to make sure I'm not opening a duplicate feature request

Description

As a developer, I want to have descriptive errors when the library fails.

Error:

invalid-style-type: when you are trying to use an invalid path.

Example:

This should raise an error:

Styles({
  style: ([isFlex1]) => isFlex ? 'fx:1' : 'fx:2'
})

This is a common mistake for computed styles that should be added inside the computed property as following:

Styles({
  computed: {
    style: ([isFlex1]) => isFlex ? 'fx:1' : 'fx:2'
  }
})

If the style type is a function outside the computed styles, we should raise an error only in development. This is an example of an error implementation: #15

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.