1.0.2 • Published 5 years ago

@expo/style-utils v1.0.2

Weekly downloads
5
License
MIT
Repository
github
Last release
5 years ago

@expo/style-utils

Components for reacting to pseudo-classes and observable styles in React Native.

Installation

yarn add @expo/style-utils

Usage - Hooks

Import the library into your JavaScript file:

import { useDimensions, useActive, useFocus, useHover } from '@expo/style-utils';

Get dimensions

const {
  window: { width, height, fontScale, scale },
  screen,
} = useDimensions();

Create pseudo class styles

import { useRef } from 'react';
import { StyleSheet, Linking, Text, Platform } from 'react-native';

import { useHover, useFocus, useActive } from './src';

function Link({ children, href = '#' }) {
  const ref = useRef(null);

  const { isHovered } = useHover(ref);
  const { isFocused } = useFocus(ref);
  const { isActive } = useActive(ref);

  return (
    <Text
      accessibilityRole="link"
      href={href}
      draggable={false}
      onPress={() => Linking.openURL(href)}
      tabIndex={0}
      ref={ref}
      style={[
        styles.text,
        isHovered && styles.hover,
        isFocused && styles.focused,
        isActive && styles.active,
      ]}>
      {children}
    </Text>
  );
}

const styles = StyleSheet.create({
  text: {
    ...Platform.select({
      web: {
        cursor: 'pointer',
        outlineStyle: 'none',
        borderBottomWidth: 1,
        borderBottomColor: 'transparent',
        transitionDuration: '200ms',
      },
      default: {},
    }),
  },
  active: {
    color: 'blue',
    borderBottomColor: 'blue',
    opacity: 1.0,
  },
  hover: {
    opacity: 0.6,
  },
  focused: {
    borderBottomColor: 'black',
  },
});

Usage - Render Props

Import the library into your JavaScript file:

import { Hoverable, Resizable } from '@expo/style-utils';

You can wrap a function or a component.

import React, { Component } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { Hoverable } from '@expo/style-utils';

const createLogger = (...msg) => () => {
  console.log(...msg);
};

class App extends Component {
  render() {
    return (
      <View>
        <Hoverable onHoverIn={createLogger('start hover')} onHoverOut={createLogger('end hover')}>
          {isHovered => (
            <TouchableOpacity accessible style={{ backgroundColor: isHovered ? '#333' : '#fff' }}>
              <Text>Welcome to React</Text>}
            </TouchableOpacity>
          )}
        </Hoverable>
      </View>
    );
  }
}

Observe window resize events.

return (
  <Resizable>
    {layout => <View style={{ width: layout.width / 2, height: layout.width / 2 }} />}
  </Resizable>
);