Code Monkey home page Code Monkey logo

react-native-shadow-2's Introduction

npm TypeScript npm PRs Welcome

react-native-shadow-2

react-native-shadow is dead for years. This is an improved version with more functionalities, Typescript support and written from scratch. It's not required to define its size: the shadow is smartly applied on the first render and then precisely reapplied on the following ones.

It solves the old React Native issue of not having the same shadow appearence and usage for Android, iOS and Web.

The ethercreative/react-native-shadow-generator website won't give you very similar results between the two platforms, for the reasons I described here. It's also not as customizable as this library.

Compatible with Android, iOS and Web. And Expo!

Supports RTL.

Give this library a quick try!

There are important breaking changes! Read it if upgrading!

Old Readme, if you are still using previous versions.

💿 Installation

1. First install react-native-svg.

The latest react-native-svg version is recommended, including if using Expo.

2. Then install react-native-shadow-2:

npm i react-native-shadow-2
# or
yarn add react-native-shadow-2

📖 Usage

import { Shadow } from 'react-native-shadow-2';

<Shadow>
  <Text style={{ margin: 20, fontSize: 20 }}>🙂</Text>
</Shadow>

Example 1


<Shadow distance={15} startColor={'#eb9066d8'} endColor={'#ff00ff10'} offset={[3, 4]}>
  <View style={{ borderTopStartRadius: 24, borderBottomEndRadius: 0, borderRadius: 10, backgroundColor: '#c454f0dd' }}>
    <Text style={{ margin: 20, fontSize: 20 }}>🤯</Text>
  </View>
</Shadow>

Example 2

Properties

All properties are optional.

Property Description Type Default
startColor The initial gradient color of the shadow. string '#00000020'
endColor The final gradient color of the shadow. string Transparent startColor. Explanation.
distance How far the shadow goes. number 10
offset Moves the shadow. Negative x moves it left/start, negative y moves it up.

Accepts 'x%' values.

Defining this will default paintInside to true, as it's the usual desired behaviour.
[x: string | number, y: string | number] [0, 0]
paintInside Apply the shadow below/inside the content. startColor is used as fill color, without a gradient.

Useful when using offset or if your child has some transparency.
boolean false, but true if offset is defined
sides The sides that will have their shadows drawn. Doesn't include corners. Undefined sides fallbacks to true. Explanation. Record<'start' | 'end' | 'top' | 'bottom', boolean> undefined
corners The corners that will have their shadows drawn. Undefined corners fallbacks to true. Explanation. Record<'topStart' | 'topEnd' | 'bottomStart' | 'bottomEnd', boolean> undefined
style The style of the View that wraps your children. Read the Notes below. StyleProp<ViewStyle> undefined
containerStyle The style of the View that wraps the Shadow and your children. Useful for margins. StyleProp<ViewStyle> undefined
stretch Make your children ocuppy all available horizontal space. Explanation. boolean false
safeRender Won't use the relative sizing and positioning on the 1st render but on the following renders with the exact onLayout sizes. Useful if dealing with radii greater than the sides sizes (like a circle) to avoid visual artifacts on the 1st render.

If true, the Shadow won't appear on the 1st render.
boolean false
disabled Disables the Shadow. Useful for easily reusing components as sometimes shadows are not desired.

containerStyle and style are still applied.
boolean false

Notes

  • If the Shadow has a single child, it will get the width, height and all of the borderRadius properties from the children's style property, if defined.

  • You may also define those properties in the Shadow's style. The defined properties here will have priority over the ones defined in the child's style.

  • If the width and height are defined in any of those, there will be only a single render, as the first automatic sizing won't happen, only the precise render.

  • You can use either the 'borderTopLeftRadius' or 'borderTopStartRadius' and their variations to define the corners radii, although I recommend the latter as it's the RTL standard.

  • Having a radius greater than its side will mess the shadow if the sizes aren't defined. You can use the safeRender property to only show the shadow on the 2nd render and beyond, when we have the exact component size and the radii are properly limited.

  • Radii greater than 2000 (Tailwind's rounded-full is 9999) may crash Android.

⁉️ FAQ

  • How to set the Shadow opacity?

    The opacity is set directly in the startColor and endColor properties, in the alpha channel. E.g.: '#0001' is an almost transparent black. You may also use '#rrggbbaa', 'rgba()', 'hsla()' etc. All patterns in this link, but not int colors, are accepted.

  • My component is no longer using the available parent width after applying the Shadow! What to do?

    Use the stretch property or style={{alignSelf: 'stretch'}} in your Shadow component. Explanation!

  • I want a preset for my Shadows!

    It's exported the ShadowProps type, the props of the Shadow component. You may do the following:

    const ShadowPresets = {
      button: {
        offset: [0, 1], distance: 1, startColor: '#0003',
      } as ShadowProps,
    };
    
    <Shadow {...ShadowPresets.button}>
  • The offset and size properties are throwing Typescript errors!

    Upgrade your Typescript to at least 4.0.0! Those two properties use labeled tuples. If you don't use Typescript, this won't happen.

📰 Popularly seen on

react-native-shadow-2's People

Contributors

greyjohnsongit avatar range-of-motion avatar srbrahma avatar think-divergent avatar timqha avatar vin-xi avatar youssefhenna 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  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-shadow-2's Issues

1 pixel line on iOS when using offset

Reopening this issue as I'm experiencing a 1-pixel line on the shadow when using offset. See below code snippet and screenshot.

<Shadow
				distance={SPACING.s12}
				viewStyle={{ alignSelf: 'stretch' }}
				radius={SPACING.s16}
				startColor={COLORS.primary}
				finalColor={COLORS.primary}
				offset={[5, 5]}
				safeRender
			>

image

Package Version:

"react-native": "0.66.4",
"react-native-svg": "^12.1.1",
"react-native-shadow-2": "^6.0.2",

Needs to set pointerEvents="box-none"

In some cases the shadow HOC will prevent clicks from registering in child components. I've only seen this behavior when shadow is used inside an animated container.

Allowing us to specify props to the container (instead of just styles) would solve this too. pointerEvents is not a valid style, it is a prop on a View.

pointerEvents="box-none" will allow clicks to pass through to children without disabling all pointer events.

Bug: The argument must be a React element, but you passed null with & weird behavior in corners - newest version

Hey @SrBrahma, thank you for the update! I (perhaps) notices a bug though.

When I upgraded to the new Version I get the following error. Am I doing something wrong?

The argument must be a React element, but you passed null.

Here I have a small code example

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import {Shadow} from "react-native-shadow-2"

export default function App() {
  return (
    <Shadow
      distance={15}
      style={{width:50, height:50}}
      startColor={'#eb9066d8'}
      endColor={'#ff00ff10'}
      offset={[3, 4]}>
      <View
        style={{
          borderTopStartRadius: 24,
          borderBottomEndRadius: 0,
          borderRadius: 10,
          backgroundColor: '#c454f0dd',
        }}>
        <Text style={{ margin: 20, fontSize: 20 }}>🤯</Text>
      </View>
    </Shadow>
  );
}

You can find a snack of the bug here:
https://snack.expo.dev/@expoco2/bug-in-react-native-shadow-2

If I delete width and height in style, I get the following error btw:
undefined is not an object (evaluating 'd.width')
Can you say something about that as well?

I am using the latest react-native version

How to convert Figma design with box-shadow

Hi,
I have design requirment to do the following shadow effect
box-shadow: 0px 3.200000047683716px 20px 0px rgba(0, 0, 0, 0.1);

How do I implement it via react-native-shadow-2?

How to apply blur radius?

Hello there.
First of all I want to thank you for this amazing library.

It's been good so far, but my shadow looks too hard.
How can I blur it? Like in css drop-shadow we have the blur property?

I want to make a shadow like this:
box-shadow: 0px 4px 15px #072A4233;

Here are the options that I passed in:

offset={[0, 4]}
startColor="#072A4233"
finalColor="transparent"

How much distance should I use? And where do I put the blur radius?

Here's the shadow in CSS:
https://codesandbox.io/s/priceless-wind-pvtwx?file=/src/styles.css
image

Here's what I did in React Native using your library:
https://snack.expo.dev/@buitrbao222/react-native-button-box-shadow
image

The results are very different.

Thanks so much for your help.

Crash on Android runtime

Hello,

When I use this library on android my app is crashing on expo-dev-client android with "react-native-shadow-2": "^6.0.4".

Expo SDK 44 -> "react-native-svg": "12.1.1"

ℹ️ EDIT: This does not crash when the Shadow is not wrapping a TouchableOpacity or doesn't provide viewStyle with an excessive borderRadius or a child with an excessive borderRadius. So It might be nice to write it somewhere in the doc or handle this case.

For tailwind user : rounded-full implementation gives 9999 as radius and looking at your code this might cause a crash with react native SVG.

For the rest of the code:

tw("bg-primary-strong rounded-full p-5")

Generate following code

{
  "backgroundColor": "rgba(244, 23, 51, 1)",
  "borderBottomLeftRadius": 9999,
  "borderBottomRightRadius": 9999,
  "borderTopLeftRadius": 9999,
  "borderTopRightRadius": 9999,
  "paddingBottom": 20,
  "paddingLeft": 20,
  "paddingRight": 20,
  "paddingTop": 20,
}

✅ Works

<TouchableOpacity activeOpacity={0.7}>
      <Shadow>
        <QRCodeIcon
          width={32}
          height={32}
          color={tailwindConfig.theme.colors.white}
        />
      </Shadow>
    </TouchableOpacity>

❌ Crash with viewStyle with excessive borderRadius

<TouchableOpacity activeOpacity={0.7}>
      <Shadow viewStyle={tw("bg-primary-strong rounded-full p-5")}>
        <QRCodeIcon
          width={32}
          height={32}
          color={tailwindConfig.theme.colors.white}
        />
      </Shadow>
    </TouchableOpacity>

⚠️ The crash seems related to 9999 value.

Old question : Crash ❌

import { QRCodeIcon } from "@modules/ui/icons/QRCodeIcon";
import React from "react";
import { TouchableOpacity } from "react-native";
import { Shadow } from "react-native-shadow-2";
import { useTailwind } from "tailwind-rn";
import tailwindConfig from "tailwind.config";

export const ScanStationButton: React.FC = () => {
  const tw = useTailwind();

  return (
    <Shadow>
      <TouchableOpacity
        activeOpacity={0.7}
        style={tw("bg-primary-strong rounded-full p-5")}
      >
        <QRCodeIcon
          width={32}
          height={32}
          color={tailwindConfig.theme.colors.white}
        />
      </TouchableOpacity>
    </Shadow>
  );
};
expo-env-info 1.0.3 environment info:
    System:
      OS: macOS 12.0.1
      Shell: 5.8 - /bin/zsh
    Binaries:
      Node: 16.14.2 - ~/.volta/tools/image/node/16.14.2/bin/node
      Yarn: 1.22.18 - ~/.volta/tools/image/yarn/1.22.18/bin/yarn
      npm: 8.5.0 - ~/.volta/tools/image/node/16.14.2/bin/npm
      Watchman: 2022.03.21.00 - /usr/local/bin/watchman
    Managers:
      CocoaPods: 1.11.3 - /usr/local/bin/pod
    SDKs:
      iOS SDK:
        Platforms: DriverKit 21.2, iOS 15.2, macOS 12.1, tvOS 15.2, watchOS 8.3
      Android SDK:
        API Levels: 26, 28, 29, 30, 31
        Build Tools: 28.0.3, 29.0.2, 29.0.3, 30.0.2
        System Images: android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom
        Android NDK: 24.0.8215888
    IDEs:
      Android Studio: 2021.1 AI-211.7628.21.2111.8309675
      Xcode: 13.2.1/13C100 - /usr/bin/xcodebuild
    npmPackages:
      expo: ~44.0.0 => 44.0.6 
      react: 17.0.1 => 17.0.1 
      react-dom: 17.0.1 => 17.0.1 
      react-native: 0.64.3 => 0.64.3 
      react-native-web: 0.17.1 => 0.17.1 
    Expo Workflow: managed

Crash log (android hermes)

FATAL EXCEPTION: main
Process: com.power.stride.staging, PID: 6412
java.lang.OutOfMemoryError
	at android.graphics.Bitmap.nativeCreate(Native Method)
	at android.graphics.Bitmap.createBitmap(Bitmap.java:1129)
	at android.graphics.Bitmap.createBitmap(Bitmap.java:1087)
	at android.graphics.Bitmap.createBitmap(Bitmap.java:1037)
	at android.graphics.Bitmap.createBitmap(Bitmap.java:998)
	at com.horcrux.svg.SvgView.drawOutput(SvgView.java:250)
	at com.horcrux.svg.SvgView.onDraw(SvgView.java:106)
	at android.view.View.draw(View.java:21594)
	at android.view.View.updateDisplayListIfDirty(View.java:20471)
	at android.view.View.draw(View.java:21326)
	at android.view.ViewGroup.drawChild(ViewGroup.java:4413)
	at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4174)
	at com.facebook.react.views.view.ReactViewGroup.dispatchDraw(ReactViewGroup.java:710)
	at android.view.View.updateDisplayListIfDirty(View.java:20462)
	at android.view.View.draw(View.java:21326)
	at android.view.ViewGroup.drawChild(ViewGroup.java:4413)
	at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4174)
	at com.facebook.react.views.view.ReactViewGroup.dispatchDraw(ReactViewGroup.java:710)
	at android.view.View.draw(View.java:21597)
	at android.view.View.updateDisplayListIfDirty(View.java:20471)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4397)
	at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4370)
	at android.view.View.updateDisplayListIfDirty(View.java:20431)
	at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:580)
	at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:586)
	at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:659)
	at android.view.ViewRootImpl.draw(ViewRootImpl.java:3871)
	at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3671)
	at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2993)
	at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1930)
	at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7988)
	at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1154)
	at android.view.Choreographer.doCallbacks(Choreographer.java:977)
	at android.view.Choreographer.doFrame(Choreographer.java:893)
	at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1139)
	at android.os.Handler.handleCallback(Handler.java:883)
	at android.os.Handler.dispatchMessage(Handler.java:100)
	at android.os.Looper.loop(Looper.java:214)
	at android.app.ActivityThread.main(ActivityThread.java:7682)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Creating Box Shadows before first render

Hello,
I tried react-native-neomorph-shadows, but the problem with the missing shadow until the first render is more or less a dealbreaker for me. Also, calling the onLayout method multiple times when navigating is also kind of heavy on the js thread, which causes dropped frames. You wrote you might have a solution to this? I´m really interesed to hear what your thoughts are. Anyway, thank you for your contribution. React native really needs better shadow support for android.

Enabling RTL on Android causes distruption in shadows

On Android (Haven't had the chance to test on iOS), the shadows get extremely distrupted upon enabling Right-to-Left layout by using React's I18nManager.forceRTL(true)

With RTL disabled, the shadows work perfectly:
image

However as soon as I enable RTL, this is what I get:
image

For anyone looking for a temporary fix, you can use the elevation property whenever RTL is enabled by checking the I18nManager.isRTL property

It seems that the ios shadow property on react native is different from what this package shows

I used the code below, but it behaves differently in the final visual display, see the image below

      <View
        style={[
          styles.square,
          {
            shadowColor: '#ffffff',
            shadowOffset: {
              width: 2,
              height: 2,
            },
            shadowOpacity: 0.8,
            shadowRadius: 9,

            // elevation: 10,
          },
        ]}>
        <View
          style={{
            borderRadius: 10,
            width: 100,
            height: 100,
            backgroundColor: 'red',
          }} />
      </View>
      <Shadow
        distance={9}
        startColor={'#FFFFFFCC'}
        finalColor={'#00000000'}
        offset={[2, 2]}>
        <View
          style={{
            borderRadius: 10,
            width: 100,
            height: 100,
            backgroundColor: 'red',
          }} />
      </Shadow>

截屏2022-02-12 下午3 53 54

expo

I want to know is it a problem with my code? If yes, can you provide the correct solution? thanks

Remove error when >1 child

Just allow the dev to have more than one child.

Having more than one child implies that the dev should set the view's style in Shadow's viewStyle prop.

Border radius problem

Hi,

I've problem on using borderRadius with this code :

    <Shadow
      style={{
        alignSelf: 'stretch',
        borderTopLeftRadius: 16,
        borderTopRightRadius: 16,
      }}
      sides={{ top: true, bottom: false, end: false, start: false }}
    >
      {children}
    </Shadow>

Top right corner is cutted

Capture d’écran 2022-12-09 à 22 24 43

Thank's !

Feature request: add support Animated

I am very helpful with this library, thank you in advance.

I hope my request can be realized, if you ask what kind of animation it is, maybe it's more towards making your own Shdow component that can be animated by prop or supported by Animated.createAnimatedComponent, whether it's from the Animated API or reanimated

1 second render issue

I have a modal that slides up from the bottom and stops halfway through the screen, I have a Shadow element wrapping the View of the modal, so it shows a backdrop shadow on the top, showing that the View is on top of the screen. Thing is, i'm seeing the shadow render in after a second, or 9/10th of a second, which makes the sliding/shadow animation really not fluid. Idk if this would be faster in a prod build, cause I have not been able to do it, but in my emulator it does look real slow. Is this a preexisting issue or it's just cause it's in an emulator? Or is there a way to optimize it?

On IOS, setting distance=0 does not work properly

On IOS, if borderRadius is set in child‘s style, distance=0 will cause an exception.
<Shadow distance={0} startColor='#E43B5F' offset={[0, 4]}> <View style={{width: 100, height: 100, borderRadius: 50, backgroundColor: 'blue'}} /> </Shadow>
shadow

Set `paintInside` default as true when `offset` is defined.

I think this would be the behaviour that everybody would like.

When setting an offset, like [0, 0.5], to have a little shadow around and below the component, it would default paintInside to true, to automatically paint the gap between the shadow start on the bottom side, and the corresponding component side, without having to set the paintInside all the time.

If someone find a cool visual case to have the gap between the offsetted shadow and the component, this person can just overwrite this default, with paintInside: false.

When not using offset, paintInside will keep its default to false, so it won't render the svg part that the user can't see, being the component opaque, saving some performance, battery life etc.

I will probably major it to avoid unexpected visuals.

Have tried to use this lib, but I can't. What am doing wrong?

Screenshot_20220926-155734_TPC Dev

  1. Margins of everything nested have to be removed
  2. Shadows in the corners are 2x thicker (spots)
  3. Round corners are not respected, actually shadows have round corners irrespectful of shape
  4. Adjacent elements - each next element just 'covers' the shadow. Setting zIndex or elevation inside does not change the picture.
    (basically helped by wrapping the top box with <View style={{ zIndex: 1}}><Shadow><View style={styles.redbox}>). So its clear - since it is a wrapper, we need to raise it a little. Though in general form of shape looks static for me .

What are the magic settings that would save me?

[Feature Request] Limit shadow radius calculation to component dimensions

The fast way to make completely round borders in React Native is to set a very high borderRadius like so:

const styles = StyleSheet.create({
  card: {
    backgroundColor: '#000',
    height: 300,
    borderRadius: 1000,
    width: 100,
  },
});

This technique have an interesting result used with react-native-shadow-2.
image

A failsafe to prevent something like this happening could be to limit the shadow calculation by the component's dimensions from the LayoutEvent Object using onLayout. The smallest value of either width or height should be used for the calculation.

Example of the calculation could look something like this:

// First get the smallest dimension of width or height
const smallestDims = e.layout.width <== e.layout.height ? e.layout.width : e.layout.height

// Second use the smallest dimension to calculate the failsafe shadow radius
const failsafeRadius = radius > smallestDims ? smallestDims / 2 : radius

Typescript: missing children on ShadowProps

I encountered the following error when using

  Property 'children' does not exist on type 'IntrinsicAttributes & ShadowProps'.ts(2322)

Even for the simplest code:

<Shadow>
      <TextInput/>
</Shadow>

I could only solve it by adding children?: ReactNode; to the ShadowProps

Implement offsets

I'd like to be able to offset my shadows either vertically or horizontally by a few pixels.

[Performance] Too much views

Hello.
I have performance issues with large amount of views generated by Shadow component.
For comparison, here are two identical screens with simple View wrapper and Shadow component wrapper.
Снимок экрана 2021-11-17 в 01 20 00
Снимок экрана 2021-11-17 в 01 20 47
The difference is almost 2 times. Can it be fixed?

x-axis offset not working as expected (iOS)

Hello,

first of all, thank you for this library!

I'm having a hard time controlling the offset x-axis value. It seems that if I simply hardcode values or use them from a state variable, the y-axis works as expected but not the x-axis. I was able to make it work by adding a useEffect (all versions are depicted in the below-mentioned snack).

Here is a snack to reproduce the issue: https://snack.expo.dev/@heyfina-dev/react-native-button-box-shadow

It seems to work on web and android but not on ios. Could you check my snack to see if I'm doing something wrong?

iOS Web
image image

The first element offset is loaded using a state variable + useEffect to set the values.
The second element offset is loaded using a state variable.
The third element offset is hardcoded.

PS: using the safeRender prop didn't help

Failed build for web

Hello, will gladly aprreciete your help.

When trying to build for web, (storybook) I got such an error

ERROR in ./node_modules/react-native-shadow-2/lib/index.js 70:41
Module parse failed: Unexpected token (70:41)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const [childHeight, setChildHeight] = react_1.useState();
| /** Defaults to true if offset is defined, else defaults to false */

const paintInside = paintInsideProp ?? (offset ? true : false);

| const [offsetX, offsetY] = offset ?? [0, 0];
| const distance = R(Math.max(distanceProp, 0)); // Min val as 0
@ ./src/components/TabNavigation/CustomTabBar/index.tsx 1:753-785
@ ./src/components/TabNavigation/CustomTabBar/CustomTabBar.stories.tsx
@ ./src sync ^.(?:(?:^|/|(?:(?:(?!(?:^|/).).)?)/)(?!.)(?=.)[^/]?.stories.(js|jsx|ts|tsx))$
@ ./.storybook/generated-stories-entry.js
@ multi ./node_modules/@storybook/core-client/dist/esm/globals/polyfills.js ./node_modules/@storybook/core-client/dist/esm/globals/globals.js ./.storybook/storybook-init-framework-entry.js ./.storybook/preview.js-generated-config-entry.js ./.storybook/generated-stories-entry.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined

Opacity can't be set for the shadow

In react-native-shadow, there is props for opacity of the shadow. How can I set the opacity with this package, or is the feature missing altogether?

Crash: RadialGradient using radius of 0

I found that the radialGradient function crashes when passed with a shadowRadius of 0

function radialGradient(id, top, left, radius, shadowRadius) {
  return (<RadialGradient id={id} cx={left ? shadowRadius : 0} cy={top ? shadowRadius : 0} r={shadowRadius} ...
}

Error

 java.lang.IllegalArgumentException: radius must be > 0
        at android.graphics.RadialGradient.<init>(RadialGradient.java:104)
        at android.graphics.RadialGradient.<init>(RadialGradient.java:67)
        at com.horcrux.svg.Brush.setupPaint(Brush.java:213)

This is the component that makes it crash

<Shadow distance={0} radius={0} startColor="#E43B5F" finalColor="#E43B5F" />

I cleaned up my code to not having to encounter this case but I am still raising this issue because I think the package could handle it more gracefully, even if it's a warning or error log and fallback to sensible values.

error show

image

<Shadow distance={10} startColor={'#E7EDF2'} finalColor={'#E7EDF2'} offset={[40, 0]} radius={10}> <View style={styles.orderHeader}> </View></Shadow>

styles.orderHeader = { width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingLeft:16, paddingRight: 16, height: 48, backgroundColor: '#fff' }

shadow version: 3.0.0
svg version: 12.1.1
``

The offset and size properties are of the wrong type.

I don't think TypeScript allows you to specify keys and their types for arrays, but the source code does.

I think it would be better to modify the ShadowProps interface like this:

interface ShadowProps {
  // ...
  offset?: (number | string)[];
  // ...
  size?: number[];
  // ...
}

Alternatively, you can use the key as follows (not recommended for compatibility reasons):

interface ShadowProps {
  // ...
  offset?: { x: number | string, y: number | string };
  // ...
  size?: { width: number, height: number };
  // ...
}

OPACITY?

This is great that I do not have to specify the size...BUT IS THERE NO OPACITY SUPPORT?
Also how can I control individual corner radius?

Web can't support more than 1 shadow.

Web Only
My web deployment of a React Native app cannot support more than one linear gradient for <Shadow> elements. New <Shadow> element gradients simply overwrite all previous gradients. I've fixed it by generating a uuid for each <Shadow> and appending it to the id string of each gradient (e.g. id={`top.${uuid}`}, fill={`url(#bottomLeft.${uuid})`}).

1 Shadow:
image
2 Shadows (notice broken corners):
image
2 Shadows with fix:
image

For my sake, let me know if this sounds like a poor solution. Also let me know if you want me to make a PR to add something like this in!

Support for Animated?

The lib has support to add shadow with Animated View?

I have a progress bar, and I'd like to put a collored shadow to emulate a neon behavior.

image

pixel gap on ios

When used on my own project on ios(plain react native project), there are obvious gaps between corners & borders. But in expo demo, it works fine.

And the shadow works fine on android. I found some docs on the documentation about the gap but can not really understand it.

Appreciated if any one can help!

shadow
reproducable code:

  <Shadow
    distance={15}
    startColor={'#000000ff'}
    finalColor={'#00000000'}
    offset={[10, 0]}
    radius={10}
    size={[100, 100]}
  >
    <View
      style={[
        {
          width: 100,
          height: 100,
          borderRadius: 10,
          backgroundColor: '#fff',
        },
      ]}
    ></View>
  </Shadow>

THIS IS NOT AN ISSUE -- Just a big thank you!

Thank you so much for creating this library. It works wonderfully for both Android and IOS. Keep up the great work!

I looked for a comment section to thank you, so I hope this is okay. Sorry for bugging your issue backlog.

Use `borderRadius` of `viewStyle`

Awesome library, using it for work right now. One suggestion:

Instead of trying to get the borderRadius of the child, also try to get it of viewStyle. Currently I have to write the following:

    <Shadow viewStyle={styles.shadowContainer} radius={styles.shadowContainer.borderRadius}>

Would be nice if this was automatically done already.

Applying Shadow shrinks my view away

As soon as I wrap my view (with containing Text) in a Shadow component, my view shrinks to the size of the Text.
Best demonstrated with pictures, before I apply Shadow :

Schermafbeelding 2022-04-13 om 10 21 20 AM

After I apply Shadow:

Schermafbeelding 2022-04-13 om 10 22 16 AM

Tested in a fresh Expo app (on Web). How to reproduce:

expo new app-simple (choose TypeScript template)
cd app-simple
yarn add react-native-svg react-native-shadow-2
(replace App.tsx with the code below)
yarn web
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { Shadow } from 'react-native-shadow-2';

export default function App() {
  return (
      <View style={styles.container}>
          <Shadow>
          <View style={styles.slide}>
              <Text style={styles.textStyle}>
                  Hello World!
              </Text>
          </View>
          </Shadow>
      </View>
  );
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'lightgrey',
    },
    slide: {
        flex: 1,
        maxWidth: '90%',
        maxHeight: '90%',
        aspectRatio: 1.777777,   // <-- I need this because the containing view can be resized, and dimensions need to stay 15:9 
        backgroundColor: 'white',
    },
    textStyle: {
        color: 'black',
    },
});

npm installation requiring --force

Installing react-native-svg as devDep in this package development was also requiring --force to be installed.

Seems to be a new npm common issue: npm/cli#2000


npm i react-native-shadow-2 
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: - @1.0.0
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"17.0.1" from the root project
npm ERR!   peer react@"*" from [email protected]
npm ERR!   node_modules/react-native-shadow-2
npm ERR!     react-native-shadow-2@"*" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"16.13.1" from [email protected]
npm ERR! node_modules/react-native
npm ERR!   react-native@"^0.63.4" from the root project
npm ERR!   peer react-native@"^0.63.4" from [email protected]
npm ERR!   node_modules/react-native-shadow-2
npm ERR!     react-native-shadow-2@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/-/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/-/.npm/_logs/2021-02-15T08_29_58_241Z-debug.log

Inner shadow

Hello, is it possible to implement inner shadow with this package?
If yes please tell how can I work with it
Thanks  🙌🏻

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.