0.4.0 • Published 9 months ago

@brantalikp/rn-resize v0.4.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

rn-resize

The rn-resize library is a toolkit for adjusting React Native styles to fit specific devices or platforms. It offers scaling utilities, dynamic theme-based styling with a useStyles hook, and easy style creation.

Supported platforms

iOSAndroidWeb

Installation

yarn add -D @brantalikp/rn-resize

Usage

Creating styles with createStyles function

You can create your styles using the createStyles function. This will create a stylesheet that automatically scales numeric values based on the screen size. Non-numeric values are left as they are. You can also provide your own base width and height values for scaling.

Supported Styles

default Values(iPhone X):

  • BaseWidth = 375;
  • BaseHeight = 812;
import { createStyles } from '@brantalikp/rn-resize';

export const styles = createStyles(
  {
    container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: 'blue',
      width: 40, //  scales horizontally
      height: 35, //  scales vertically
    },
    text: {
      fontSize: 12, // Scales the value according to the device.
    },
  },
  { baseWidth: 360, baseHeight: 640 } // optional
);

Platform Specific Styles

You can define styles for a specific platform.

iOSAndroidWebTablet
iOS ScreenshotAndroid ScreenshotWeb ScreenshotTablet Screenshot
export const styles = createStyles({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
    web: {
      backgroundColor: 'pink',
    },
    ios: {
      backgroundColor: 'green',
    },
    android: {
      backgroundColor: 'blue',
    },
    tablet: {
      backgroundColor: 'red',
    },
  },
  text: {
    fontSize: 40,
    fontWeight: 'bold',
    web: {
      color: 'red',
    },
    android: {
      fontSize: 30,
      color: 'white',
    },
  },
});

Creating themed styles

  • If you are using a theme in your application, you can create styles that use the theme properties.

To use a theme in your application and get TypeScript type checking and autocompletion, you will first need to create your styles with the MakeStylesProps helper from the library.

// theme.ts
import { MakeStylesProps } from '@brantalikp/rn-resize';

export const myCustomTheme = {
  colors: {
    background: 'pink',
  },
} as const;

type Theme = typeof myCustomTheme;

export type CreateStyles<T extends string> = MakeStylesProps<T, Theme>;

Then you need to wrap your application with the ThemeProvider and provide it your theme.

Options:

Optionvalue
baseWidthnumber (optional)
baseHeightnumber (optional)
import { ThemeProvider } from '@brantalikp/rn-resize';
import { myCustomTheme } from './theme';

function App() {
  return (
    <ThemeProvider theme={theme} options={options}>
      {/* Your application */}
    </ThemeProvider>
  );
}

export default App;

Then, you can create styles using your theme.

import { createStyles } from './theme';

type StylesKeys = 'container' | 'text'; // Ensures that the useStyles hook provides autocompletion for style keys.

export const styles: CreateStyles<StylesKeys> = (theme) => ({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
    alignItems: 'center',
    justifyContent: 'center',
    ios: {
      paddingTop: 20,
    },
  },
  text: {
    fontSize: 50,
    fontWeight: 'bold',
    color: theme.colors.text,
  },
});

Finally, in your components, you can use the useStyles hook to access the themed styles

import { useStyles } from '@brantalikp/rn-resize';
import { styles } from './styles';

const MyComponent = () => {
  const { container, text } = useStyles(styles);

  return (
    <View style={container}>
      <Text style={text}>My App</Text>
    </View>
  );
};

Using useTheme hook

If you want to access or modify the theme, you can use the useTheme hook.

import { useTheme } from '@brantalikp/rn-resize';
import { ThemeType } from './theme'

const MyComponent = () => {
const { theme, setTheme } = useTheme<ThemeType>();

  // Access theme props
  console.log(theme.colors.background);

  // Update the theme
  const updateTheme = () => {
    setTheme({ colors: { background: 'red' } });
  };

  return (
    //
  );
}

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT


Made with create-react-native-library

abort-controllerabsolute-pathacceptsacornacorn-jsxacorn-walkadd-streamagent-baseaggregate-errorajvanseransi-alignansi-escapesansi-fragmentsansi-regexansi-stylesanymatchappdirsjsargargparsearr-diffarr-flattenarr-unionarray-buffer-byte-lengtharray-ifyarray-includesarray-unionarray-uniquearray.prototype.flatmaparray.prototype.maparray.prototype.tosortedarrifyasapassign-symbolsast-typesastral-regexasyncasync-limiterasync-retryatobavailable-typed-arraysbabel-corebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-syntax-trailing-function-commasbabel-preset-current-node-syntaxbabel-preset-fbjsbabel-preset-jestbalanced-matchbasebase64-jsbasic-ftpbefore-after-hookbig-integerblboxenbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-frombundle-namebytescache-basecacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litechalkchar-regexchardetci-infocjs-module-lexerclass-utilsclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepcocollect-v8-coveragecollection-visitcolor-convertcolor-namecolorettecommand-existscommandercommondircompare-funccomponent-emittercompressiblecompressionconcat-mapconcat-streamconfig-chainconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcopy-descriptorcore-js-compatcore-util-iscosmiconfigcreate-requirecross-spawncrypto-random-stringcsstypedargsdata-uri-to-bufferdateformatdayjsdebugdecamelizedecamelize-keysdecode-uri-componentdecompress-responsededentdeep-extenddeep-isdeepmergedefault-browserdefault-browser-iddefaultsdefer-to-connectdefine-lazy-propdefine-propertiesdefine-propertydegeneratordeldenodeifydepddeprecated-react-native-prop-typesdeprecationdestroydetect-newlinediffdiff-sequencesdir-globdoctrinedot-propeastasianwidthee-firstelectron-to-chromiumemitteryemoji-regexencodeurlend-of-streamenvinfoerror-exerror-stack-parsererrorhandleres-abstractes-array-method-boxes-properlyes-get-iteratores-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslint-plugin-eslint-commentseslint-plugin-ft-floweslint-plugin-jesteslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimexecaexitexpand-bracketsexpectextend-shallowexternal-editorextglobfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfast-xml-parserfastqfb-watchmanfetch-blobfiguresfile-entry-cachefill-rangefinalhandlerfind-cache-dirfind-upflat-cacheflattedflow-parserfor-eachfor-inform-data-encoderformdata-polyfillfragment-cachefreshfs-extrafs.realpathfseventsfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-pkg-repoget-streamget-symbol-descriptionget-uriget-valuegit-raw-commitsgit-remote-origin-urlgit-semver-tagsgit-upgit-url-parsegitconfiglocalglobglob-parentglobal-dirsglobalsglobalthisglobbygopdgotgraceful-fsgrapheme-splittergraphemerhandlebarshard-rejectionhashas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-valuehas-valueshas-yarnhermes-estreehermes-parserhermes-profile-transformerhosted-git-infohtml-escaperhttp-cache-semanticshttp-errorshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthuman-signalsiconv-liteieee754ignoreimage-sizeimport-freshimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipis-absoluteis-accessor-descriptoris-argumentsis-array-bufferis-arrayishis-bigintis-boolean-objectis-bufferis-callableis-ciis-core-moduleis-data-descriptoris-date-objectis-descriptoris-directoryis-dockeris-extendableis-extglobis-fullwidth-code-pointis-generator-fnis-git-dirtyis-git-repositoryis-globis-inside-containeris-installed-globallyis-interactiveis-mapis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-regexis-relativeis-setis-shared-array-bufferis-sshis-streamis-stringis-symbolis-text-pathis-typed-arrayis-typedarrayis-unc-pathis-unicode-supportedis-weakrefis-windowsis-wslis-yarn-globalisarrayisexeisobjectissue-parseristanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsiterate-iteratoriterate-valuejest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-serializerjest-snapshotjest-utiljest-validatejest-watcherjest-workerjetifierjoijs-tokensjs-yamljsc-androidjsc-safe-urljscodeshiftjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonparseJSONStreamjsx-ast-utilskeyvkind-ofkleurlatest-versionlevenlevnlines-and-columnsload-json-filelocate-pathlodashlodash.camelcaselodash.capitalizelodash.debouncelodash.escaperegexplodash.isfunctionlodash.ismatchlodash.isplainobjectlodash.isstringlodash.kebabcaselodash.mergelodash.mergewithlodash.snakecaselodash.startcaselodash.throttlelodash.uniqlodash.uniqbylodash.upperfirstlog-symbolslogkittyloose-envifylowercase-keyslru-cachemacos-releasemake-dirmake-errormakeerrormap-cachemap-objmap-visitmemoize-onemeowmerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-hermes-compilermetro-inspector-proxymetro-minify-tersermetro-minify-uglifymetro-react-native-babel-presetmetro-react-native-babel-transformermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsmixin-deepmkdirpmodify-valuesmsmute-streamnanomatchnatural-comparenatural-compare-litenegotiatorneo-asyncnetmasknew-github-release-urlnice-trynocachenode-dirnode-domexceptionnode-fetchnode-int64node-releasesnode-stream-zipnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsob1object-assignobject-copyobject-inspectobject-keysobject-visitobject.assignobject.entriesobject.fromentriesobject.hasownobject.pickobject.valueson-finishedon-headersonceonetimeopenoptionatororaos-nameos-tmpdirp-cancelablep-finallyp-limitp-locatep-mapp-trypac-proxy-agentpac-resolverpackage-jsonparent-moduleparse-jsonparse-pathparse-urlparseurlpascalcasepath-existspath-is-absolutepath-keypath-parsepath-typepicocolorspicomatchpifypiratespkg-dirposix-character-classesprelude-lsprettier-linter-helperspretty-formatprocess-nextick-argspromisepromise.allsettledpromptsprop-typesproto-listprotocolsproxy-agentproxy-from-envpumppunycodepupaqqueue-microtaskquick-lrurange-parserrcreact-devtools-corereact-domreact-isreact-native-codegenreact-native-gradle-pluginreact-refreshreact-shallow-rendererread-pkgread-pkg-upreadable-streamreadlinerecastrechoirredentregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregex-notregexp.prototype.flagsregexpu-coreregistry-auth-tokenregistry-urlregjsparserrepeat-elementrepeat-stringrequire-directoryrequire-from-stringrequire-main-filenameresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve-urlresolve.exportsresponselikerestore-cursorretretryreusifyrimrafrun-applescriptrun-asyncrun-parallelrxjssafe-buffersafe-regexsafe-regex-testsafer-bufferschedulersemversemver-diffsendserialize-errorserve-staticset-blockingset-valuesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsside-channelsignal-exitsisteransislashslice-ansismart-buffersnapdragonsnapdragon-nodesnapdragon-utilsockssocks-proxy-agentsource-mapsource-map-resolvesource-map-supportsource-map-urlspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit-stringsplit2sprintf-jsstack-utilsstackframestacktrace-parserstatic-extendstatusesstdin-discarderstop-iteration-iteratorstring_decoderstring-lengthstring-natural-comparestring-widthstring.prototype.matchallstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstrip-ansistrip-bomstrip-eofstrip-final-newlinestrip-indentstrip-json-commentsstrnumsudo-promptsupports-colorsupports-hyperlinkssupports-preserve-symlinks-flagtempterminal-linktersertest-excludetext-extensionstext-tablethroatthroughthrough2titleizetmptmplto-fast-propertiesto-object-pathto-regexto-regex-rangetoidentifiertr46trim-newlinestslibtsutilstype-checktype-detecttype-festtyped-array-lengthtypedarraytypedarray-to-bufferuglify-esuglify-jsunbox-primitiveunc-path-regexunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunion-valueunique-stringuniversal-user-agentuniversalifyunpipeunset-valueuntildifyupdate-browserslist-dbupdate-notifieruri-jsurixurl-joinuseuse-sync-external-storeutil-deprecateutils-mergev8-compile-cache-libv8-to-istanbulvalidate-npm-package-licensevaryvlqvm2walkerwcwidthweb-streams-polyfillwebidl-conversionswhatwg-fetchwhatwg-urlwhichwhich-boxed-primitivewhich-modulewhich-typed-arraywidest-linewildcard-matchwindows-releaseword-wrapwordwrapwrap-ansiwrappywrite-file-atomicwsxdg-basedirxtendy18nyallistyamlyargsyargs-parserynyocto-queue
0.4.0

9 months ago

0.3.0

10 months ago

0.2.1

10 months ago

0.2.0

10 months ago

0.1.9

10 months ago

0.1.8

10 months ago

0.1.7

10 months ago

0.1.6

10 months ago

0.1.5

10 months ago

0.1.4

10 months ago

0.1.3

10 months ago

0.1.2

10 months ago

0.1.1

10 months ago

0.1.0

11 months ago