Create responsive design with the help of css queries

Overview

react-native-css-stylesheet

Create responsive design with the help of css queries

Installation

npm install react-native-css-stylesheet

Usage

Define styles using CssStyleSheet.create() instead of StyleSheet.create()

import React from "react";
import { Text, View } from "react-native";

import CssStyleSheet from "react-native-css-stylesheet";

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

const { styles } = CssStyleSheet.create({
	text: {
		"(orientation: landscape)": {
			fontSize: "3rem",
		},
		fontSize: "2rem",
		marginVertical: 20,
	},
	container: {
		alignItems: "center",
		flex: 1,
		justifyContent: "center",
	},
});

Styling Options

Size with custom units

Unit Description Example
<size>s scales size in a linear manner relative to screen width 7.5s
<size>vs scales size in a linear manner relative to screen height 9vs
<size>ms<factor> scales size in a linear manner relative to screen width. factor is resize factor. Default is 0.5 7ms or 7ms0.25
<size>mvs<factor> scales size in a linear manner relative to screen height. factor is resize factor. Default is 0.5 9ms or 9ms0.75
<size>rem size relative to the default font size 1rem
<size>vw size relative to the window width 1.02vw
<size>vh size relative to the window height 10vh
<size>vmin size relative to the shortest dimension compared between window width and height 10vmin
<size>vmax size relative to the largest dimension compared between window width and height 10vmax

Note:

  1. size can be any positive number (including decimal) for s, vs, ms, and mvs
  2. size can be any positive number ranging from 0 to 100 (including decimal) for rem, vw, vh, vmin, and vmax
  3. factor can be any positive number ranging from 0 and 1 (including decimal)

Queries

Query Supported Values Description Example
(orientation: <value>) portrait or landscape Matches the orientation with the provided value 1. (orientation: landscape)
2. (orientation: portrait)
(min-width: <value>) custom size or number Matches the minimum window width with the provided value. 1. (min-width: 320)
2. (min-width: 10s)
(max-width: <value>) custom size or number Matches the maximum window width with the provided value. 1. (max-width: 600)
2. (max-width: 10rem)
(min-height: <value>) custom size or number Matches the minimum window height with the provided value. 1. (min-height: 600)
2. (min-height: 15vs)
(max-height: <value>) custom size or number Matches the maximum window height with the provided value. 1. (max-height: 1200)
2. (max-height: 25mvs0.75)

Note:

  1. Brackets around queries are compulsory.
  2. Any custom size defined in the above section will work, but using units like vw, vh, vmin, or vmax would always result in true since they are relative to the window with and height.

Grouping Queries

Keyword Description Example
<query> and <query> Applies the styles if queries preceding and succeeding to the keyword and is true. (orientation: landscape) and (min-width:320)
<query> , <query> Applies the styles if either of the queries preceding and succeeding to the keyword , is true. (min-height: 600) , (min-width:320)
(<queries>) Create group of queries if you have more than one conditional keyword ((orientation: landscape) and (min-width:320)),((orientation: portrait) and (min-height:600))

API

create (styles)

A function which returns computed styles on the basis of media queries specified.

Arguments

  1. styles (object) : A style object either the normal or with custom properties and queries.

Return

  • cssStyleSheet (object)

    • styles (object): A style object which is generated during application start. See basic example above.

    • responsiveStyles (Function): A function to regenerate the styles during run time. When used inside a component, it will generate a new style object every time the component updates. See example below.

Example

import React from "react";
import { Text, View } from "react-native";

import CssStyleSheet from "react-native-css-stylesheet";

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

const { responsiveStyles } = CssStyleSheet.create({
	text: {
		"(orientation: landscape)": {
			fontSize: "3rem",
		},
		fontSize: "2rem",
		marginVertical: 20,
	},
	container: {
		alignItems: "center",
		flex: 1,
		justifyContent: "center",
	},
});

useCssStyleSheet (responsiveStyles)

Hook which returns recalculated styles every time there is a dimension change.

Arguments

  1. responsiveStyles (Function) : responsiveStyles function returned from create function.

Return

  • styles (object): An object which is recalculated every time dimension change happens. See example below.

Example

import React from "react";
import { Text, View } from "react-native";

import CssStyleSheet, { useCssStyleSheet } from "react-native-css-stylesheet";

const ResponsiveFunctionExample = () => {
	const styles = useCssStyleSheet(responsiveStyles);
	return (
		<View style={styles.container}>
			<Text style={styles.text}>ResponsiveFunctionExample</Text>
		</View>
	);
});

const { responsiveStyles } = CssStyleSheet.create({
	text: {
		"(orientation: landscape)": {
			fontSize: "3rem",
		},
		fontSize: "2rem",
		marginVertical: 20,
	},
	container: {
		alignItems: "center",
		flex: 1,
		justifyContent: "center",
	},
});

export default ResponsiveFunctionExample;

withCssStyleSheet (responsiveStyles, Component)

Link a style sheet with a component using the higher-order component pattern. It does not modify the component passed to it; instead, it returns a new component with a cssStyleSheet prop. This prop contains the responsive style object which gets recalculated every time there is a dimension change detected. This props can be used as a normal style object.

  • It adds a cssStyleSheet prop.
  • It forwards refs to the inner component.

Arguments

  1. responsiveStyles (Function) : responsiveStyles function returned from create function.

  2. Component (React Element) : The component that will be wrapped

Return

  • Component (React Element): The new component created.

Example

import React from "react";
import { Text, View } from "react-native";

import CssStyleSheet, { withCssStyleSheet } from "react-native-css-stylesheet";

class ClassWithoutStyleSheet extends React.Component {
	render() {
		const { cssStyleSheet } = this.props;
		return (
			<View style={cssStyleSheet.container}>
				<Text style={cssStyleSheet.text}>ResponsiveClassExample</Text>
			</View>
		);
	}
}

const { responsiveStyles } = CssStyleSheet.create({
	text: {
		"(orientation: landscape)": {
			fontSize: "3rem",
		},
		fontSize: "2rem",
		marginVertical: 20,
	},
	container: {
		alignItems: "center",
		flex: 1,
		justifyContent: "center",
	},
});

const ResponsiveClassExample = withCssStyleSheet(responsiveStyles, ClassWithoutStyleSheet);

export default ResponsiveClassExample;

/**
 * OR
 * export default withCssStyleSheet(responsiveStyles, ClassWithoutStyleSheet);
 */

Todo

  • Add Examples screenshot/gif
  • Nested queries support
  • Platform based media queries

License

MIT

You might also like...

A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles.

A highly impartial suite of React components that can be assembled by the consumer to create a carousel with almost no limits on DOM structure or CSS styles. If you're tired of fighting some other developer's CSS and DOM structure, this carousel is for you.

Dec 24, 2021

Single function to create, manage, compose variants, for any CSS-in-JS libraries.

Build-variants Single function to create, manage, compose variants, for any CSS-in-JS libraries. Motivation Before diving into the implementation deta

Jan 2, 2023

A small tool to help you check package duplicates in `yarn.lock`

A small tool to help you check package duplicates in `yarn.lock`

Yarn Duplicate A small tool to help you check duplicate package and package size in yarn.lock. Usage Change to your project root folder, which have a

Aug 11, 2021

An application to help in the automatic booking of COVID vaccination slots in India whenever they become available.

An application to help in the automatic booking of COVID vaccination slots in India whenever they become available.

Co-WIN automated slot booking Automatically book vaccine slots as and when they become available This application aims to automatically book vaccine s

Nov 23, 2022

Juka Official Website built on top of Docusaurus/React Framework. Help us make it better!

Juka Programming Language Juka Programming Language website is built on top of Docusaurus 2. Feel free to contribute to our website! Any help is appre

Dec 24, 2022

This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

React-compress This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundl

Jan 6, 2023

Webpack is an open-source JavaScript module bundler. This includes basic setup files to help me not redo all the setups for webpack when starting a new project.

Webpack Setup Webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript, but it can transform front-end assets such as

Jun 23, 2022

A system for sharing tests between students. In RepoProvas anyone can look up old tests for their subjects and teachers or send old tests to help other students!

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 10, 2022

This a programming training app, aimed to help OMRI's students learng the magic world of programming.

OMRI App (fe-omri-app) This a programming training app, aimed to help OMRI's students learng the magic world of programming. Install the dependencies

Nov 19, 2022
Comments
  • chore(deps): bump react-native from 0.63.4 to 0.64.1 in /example

    chore(deps): bump react-native from 0.63.4 to 0.64.1 in /example

    Bumps react-native from 0.63.4 to 0.64.1.

    Release notes

    Sourced from react-native's releases.

    v0.64.1

    This patch release is specifically targetted towards fixing iOS build problems in Xcode 12.5. If it doesn't help, please refer to this issue.

    Aside from bumping your version from 0.64.0 to 0.64.1, please check your podfile.lock and make sure that Flipper is on 0.75 or higher, and Flipper-Folly is 2.5.3 or higher; if not, add this line to your podfile (or modify it if you already had it):

    use_flipper!('Flipper' => '0.75.1', 'Flipper-Folly' => '2.5.3', 'Flipper-RSocket' => '1.3.1')
    

    After which, do all the classic necessary cleans (node_modules, caches, pod folders, etc)(react-native-clean-project is your ally) then do yarn install and a pod install --repo-update (if pod install fails on an error about a Flipper package, just remove the relevant lines from the podfile.lock and run the pod install again).

    The only other commit picked & released along the Xcode 12.5 fixes is:

    • Update validateBaseUrl to use latest regex (commit) which fixes CVE-2020-1920, GHSL-2020-293.

    You can participate in the conversation on the status of this release at this issue.


    To help you upgrade to this version, you can use the upgrade helper ⚛️


    You can find the whole changelog history over at react-native-releases.

    v0.64.0

    0.64 stable is here 🎉

    Thanks to everyone who contributed and helped to get this together, everyone worked really hard and we hope you are as excited as we are 🤗

    Some of the most important highlights of this version:

    • Hermes opt-in on iOS
    • Inline Requires enabled by default
    • React 17

    Among many others - please refer to the blog post for more details.


    You can participate in the conversation on the status of this release at this issue.


    You can upgrade to this version using the upgrade helper webtool ⚛️ And if you are having trouble, please refer to the new Upgrade Support repository by our awesome community.


    ... (truncated)

    Changelog

    Sourced from react-native's changelog.

    v0.64.1

    Fixed

    iOS specific

    Security

    v0.64.0

    Breaking

    Android specific

    iOS specific

    Deprecated

    Android specific

    • Deprecated method UIManagerModule.getUIImplementation. This method will not be part of the new architecture of React Native. (fe79abb32c by @​mdvacca)

    Added

    ... (truncated)

    Commits
    • 787567a [0.64.1] Bump version numbers
    • cf8a364 [local] change post-install to patch RTC-Folly
    • 1c4ac48 [local] yarn lock update (?)
    • 76f45d3 [local] update RNTester files for 0.64
    • 3912fef Update validateBaseUrl to use latest regex
    • ace025d [0.64.0] Bump version numbers
    • 728d55a Fixing the git attrs for all the people and all the files and all future 🙌
    • 8a6ac1f chore: Update React.podspec to require cocoapods >= 1.10.1
    • 138fdbc fix: restore refresh control fix
    • 7f3f80f Fix RefreshControl layout when removed from window (#31024)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Owner
Darshan Jain
Darshan Jain
Material-UI is a simple and customizable component library to build faster, beautiful, and more accessible React applications. Follow your own design system, or start with Material Design.

Material-UI Quickly build beautiful React apps. Material-UI is a simple and customizable component library to build faster, beautiful, and more access

Material-UI 83.6k Dec 30, 2022
TryShape is an open-source platform to create shapes of your choice using a simple, easy-to-use interface. You can create banners, circles, polygonal shapes, export them as SVG, PNG, and even as CSS.

Create, Export, Share, and Use any Shapes of your choice. View Demo · Report Bug · Request Feature ?? Introducing TryShape TryShape is an opensource p

TryShape 148 Dec 26, 2022
Choosy is a mobile application that allows users to create photo polls that others can vote on and help declare which photo is the best.

Choosy - Create photo polls The freshest mobile application for your photo polls! Explore the docs » Table of Contents Introduction App concept Target

Choosy 13 Sep 7, 2022
A set of React components implementing Google's Material Design specification with the power of CSS Modules

React Toolbox is a set of React components that implement Google's Material Design specification. It's powered by CSS Modules and harmoniously integra

React Toolbox 8.7k Dec 30, 2022
A draggable and resizable grid layout with responsive breakpoints, for React.

React-Grid-Layout React-Grid-Layout is a grid layout system much like Packery or Gridster, for React. Unlike those systems, it is responsive and suppo

RGL 16.9k Jan 4, 2023
React.js Responsive Minimal Carousel

React Carousel Minimal Easy to use, responsive and customizable carousel component for React Projects. Installation npm i react-carousel-minimal Demo

Sahil Saha 82 Dec 23, 2022
Plock is a responsive masonry layout implementation for React. Very simple to use and easy to understand.

About Plock ?? Plock is a responsive masonry layout implementation for React. Very simple to use and easy to understand. Can I see a demo? ?? The demo

Renato Pozzi 130 Dec 9, 2022
A simple and responsive quizlet-like flashcard component with a few additional options

Welcome to react-quizlet-flashcard ?? A simple and responsive quizlet-like flashcard component with a few additional options. Front and back card acce

A.B.Santhosh 14 Dec 17, 2022
here in this git repo you will get react js basic layout, having in responsive mode.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 3 Feb 23, 2022
An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) products using an API in which you can also create, read, update or delete products.

CRUD app with React and Firebase 9 An application that has a frontend (user interface) that allows you to create, read, update or delete (CRUD) produc

Júlio Bem 3 Sep 28, 2021