• Stars
    star
    364
  • Rank 117,101 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A responsive utility toolkit for React Native πŸ“±βš›

Responsive applications are a big challenge for mobile developers.

Most of the mobile devices have different dimensions and densities, so using absolute units like pixels ('px') can cause elements to have different sizes than expected.

As iPhones, for example, have a higher pixel density than Android phones, if you use 16px in a Text, it will look much larger on Android than on iOS.

This library aims to solve this problem by converting this value from px to rem. The value in rem is calculated with some variables such as device width and height, thus providing a much more proportional interface.

It also includes an easy way to create Media Queries just like the web environment but based on breakpoints as inside mobile devices we do not need to deal a lot with screen resizing while the app is running.

Getting started

Install the library using:

yarn add responsive-native react-native-safe-area-context

The lib react-native-safe-area-context must be installed.

Wrap the application with the provider

You can import the ScreenProvider and wrap the whole App with it then all child components will be able to consume and use the responsive functions.

Set the baseFontSize

ScreenProvider receives a optional baseFontSize prop that corresponds to the value of 1rem. By default 1rem = 16px, but depending on your UI, you would prefer setting this to a different value to provide an easier way to achieve some values in spacings or sizes.

import { ScreenProvider } from 'responsive-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';

export default function App() {
  return (
    <SafeAreaProvider>
      <ScreenProvider baseFontSize={16}>
        { ... }
      </ScreenProvider>
    </SafeAreaProvider>
  )
}

ScreenProvider depends on SafeAreaProvider, from react-native-safe-area-context, so put SafeAreaProvider around ScreenProvider.

Library hooks

useRem

Transforms a rem value to the best pixel value based on the device width, height and accessibility preferences.

The useRem hook receives as first param the value in rem that will be converted to pixels. The second optional parameter is shouldScale that is a boolean (defaults to false) that tells if the fontScale defined by the user device should be used in the conversion (if you're using rem to define font sizes, you might want to use this as true).

You can read a little more about fontScale here

export function MyComponent() {
  const rem = useRem();

  return (
    <View style={styles.container}>
      <Text style={[styles.text, { fontSize: rem(1.5, true) }]}>Hello World!</Text>
    </View>
  );
}

useMediaQuery

Returns true if the conditions match the device.

The useMediaQuery hook receive as params:

{
  platform: 'ios' | 'android' | 'web' | 'windows' | 'macos';
  minBreakpoint: 'sm' | 'md' | 'lg' | 'xlg';
  maxBreakpoint: 'sm' | 'md' | 'lg' | 'xlg';
}
export function MyComponent() {
  const showSideNav = useMediaQuery({
    minBreakpoint: 'lg',
  });

  return (
    <View style={styles.container}>
      { showSideNav ? <SideNav /> : <DefaultNav /> }
    </View>
  );
}

useBreakpointValue

Returns the desired value based on the breakpoint.

You can pass different values so your interface will adapt devices different sizes. The useBreakpointValue hook can return any value, including JSX elements. The base value is always required and will be used if the device breakpoint was not matched by the other rules.

export function MyComponent() {
  const textByBreakpoint = useBreakpointValue({
    sm: "I'm a small device",
    md: "I'm a medium device",
    base: "I will be used in any larger device than md",
  });

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{textByBreakpoint}</Text>
    </View>
  );
}

useScreen

Returns an object with important information about the device screen.

{
  padding: {
    top: number;
    bottom: number;
    left: number;
    right: number;
  };
  breakpoint: {
    size: 'sm' | 'md' | 'lg' | 'xlg';
    maxWidth: number;
  };
  pixelRatio: number;
  fontScaleFactor: number;
  baseFontSize: number;
}

You might want use useScreen to get information like padding so you can use it on Header or TabBar components so it doesn't stay under non-clickable areas.

Integration

styled-components

If you're using styled-components, you can integrate this library functionality into your ThemeProvider.

Create a new ThemeProvider based on this example and use it instead of the standard styled-components ThemeProvider.

Typescript

If you're using TypeScript, you'll have to add the responsive-native functions along with your theme typings, just follow the example.

Usage

import styled from 'styled-components/native';

export const Container = styled.Text`
  font-size: ${({ theme }) => theme.screen.rem(12)}px;
`;

We know, this is the shortest syntax, so we created an example VSCode snippet so you can add it inside VSCode and just type 'rem' and it will autocomplete for you.

Contributing

Thank you for being interested in making this package better. We encourage everyone to help improve this project with new features, bug fixes, or performance improvements. Please take a little bit of your time to read our guide to make this process faster and easier.

Contribution Guidelines

To understand how to submit an issue, commit and create pull requests, check our Contribution Guidelines.

License

MIT License Β© Diego Fernandes

More Repositories

1

rocketredis

A beautiful Redis GUI πŸ”₯ (under development)
TypeScript
1,910
star
2

electron-typescript-react

:electron: An Electron boilerplate including TypeScript, React, Jest and ESLint.
JavaScript
1,437
star
3

video-to-reels

Automatically edit videos to post on Instagram Reels
JavaScript
663
star
4

umbriel

βœ‰οΈ Umbriel is a simple mailing platform built with Node.js, TypeScript & Prisma.
TypeScript
517
star
5

node-microservices-ddd

🚒 Node.js microservice structure with DDD & Monorepo
TypeScript
491
star
6

rsxp-2023

RepositΓ³rio contendo o cΓ³digo do app do RS/XP 2023
TypeScript
438
star
7

faladev

Meu site pessoal onde deixo todas minhas configuraçáes atuais como do Visual Studio Code, Fish e informaçáes sobre meu setup.
TypeScript
247
star
8

flowly

Flowly helps you document your event driven architecture across your team.
TypeScript
211
star
9

microservices-base-decode

Application made for the Decode #20 (Microservices fundaments)
TypeScript
186
star
10

mux-batch-import

Import a list of videos to Mux with ease πŸ“ΉπŸ”₯
TypeScript
161
star
11

umbriel-dashboard

TypeScript
139
star
12

expo-pomodoro-app

⏰ App de Pomodoro construído durante o Meetup Frontend SP
JavaScript
135
star
13

diego3g

132
star
14

react-hooks-redux-example

Exemplo de aplicação utilizando React Hooks no Redux
HTML
131
star
15

ai-tools

ai-tools
TypeScript
128
star
16

performance-react

βš›οΈ CΓ³digo produzido no workshop de "Performance com React" para o meetup Facebook Developers Circle
JavaScript
116
star
17

gcloud-node-video-transcoding

πŸ“ΉπŸ”₯ Transcode Google Cloud Storage video files with Node.js and FFmpeg
TypeScript
112
star
18

node-prisma-twitter

A Twitter clone made with Node.js, TypeScript and Prisma ❀️
TypeScript
99
star
19

react-data-fetching

TypeScript
97
star
20

react-native-responsive-hooks

TypeScript
91
star
21

react-unit-testing

TypeScript
65
star
22

next-aws

TypeScript
64
star
23

next-supabase-fullcycle

TypeScript
63
star
24

node-arch

TypeScript
60
star
25

ignite-lab-react

TypeScript
60
star
26

react-example-useswr

TypeScript
59
star
27

ignite-nitro-design

nitro2
TypeScript
55
star
28

webcontainers-test

livedocs
TypeScript
54
star
29

jamstack-next-graphcms

TypeScript
48
star
30

jivia-godot

An Action RPG created to learn Game Development.
GDScript
48
star
31

nextjs-chakra

NextJS studies with Chakra UI
TypeScript
41
star
32

serverless-typescript-starter

Starter pack to create serverless functions with TypeScript
JavaScript
38
star
33

05-design-system

Design system construΓ­do no Ignite
TypeScript
35
star
34

keycloak-nextjs-example

Example Next.js project with Keycloak authentication (SSR & Refresh Token)
TypeScript
34
star
35

react-webpack-swc

ReactJS webpack configuration example using SWC
JavaScript
34
star
36

blog-graphql-prisma

Back-end de um blog utilizando Node/GraphQL/Prisma.
TypeScript
32
star
37

next-and-cra-serverless

JavaScript
31
star
38

node-ffmpeg-hls-encryption

Some tests using FFMpeg to transcode video to multiple resolutions with AES-128 encryption.
TypeScript
29
star
39

next-basics

Created with StackBlitz ⚑️
TypeScript
27
star
40

nivo

Nivo helps you distributing fast and secure video content managing all the complex stuff to you.
TypeScript
26
star
41

graphql-nexus-example

Sample API developed with GraphQL Nexus, TypeScript and Prisma
TypeScript
25
star
42

video-nugget-creator

Tool to create "nuggets" from Youtube videos.
JavaScript
24
star
43

figma-jam-ui-react

Cloning the Figma Jam UI with React
TypeScript
24
star
44

jivia

2D RPG Game with React + Electron
JavaScript
23
star
45

nextjs-dogs

JavaScript
22
star
46

dokr

Fala galera da live de React
JavaScript
21
star
47

pulumi-lambda-mail-queue

TypeScript
20
star
48

project-template-next.js

Next.js template for CodeSandbox Projects
TypeScript
20
star
49

vitest-decorators

vitest-decorators
TypeScript
17
star
50

node-deploy

node-deploy
TypeScript
16
star
51

nest-sls-starter

A simple NestJS Serverless starter
15
star
52

tars

Gamification bot made with Rust (Just studying)
Rust
15
star
53

remix-on-cloudflare-pages

TypeScript
14
star
54

context-example

TypeScript
13
star
55

node-queue-benchmarks

JavaScript
12
star
56

next-graphql-codegen

TypeScript
11
star
57

tedx-app

Aplicativo do TEDx em Rio do Sul
JavaScript
11
star
58

setup-next-13-neon

TypeScript
10
star
59

test-meilisearch

TypeScript
8
star
60

nextvercel

JavaScript
7
star
61

large-json-node-stream-process

Process large JSON inputs with Streams in Node.js
TypeScript
5
star
62

test-figma-tokens

figma-tokens
JavaScript
5
star
63

searchable-react-select

A simple React searchable select using Radix UI
TypeScript
3
star
64

cranetlify

TypeScript
1
star