How to apply shadow to react native View without affecting inner view elements?

Viewed 6924

Please click on image

I would like to know how to apply shadow only to the main outer view. Here on applying shadow, it's getting applied to all the inner elements

4 Answers

The trick to make the shadow props of parent don't inherit to children element, is to set a background color to the component on which you set the shadow. For example that would be:

<View 
  style={{ backgroundColor: '#fff' }}
  shadowOffset={{height: 10}}
  shadowColor='black'
  shadowOpacity={0.5}
>
  <Text>{title}</Text>
</View>

Unfortunately this only works with colored backgrounds – when setting a transparent background with RGBA or 'transparent' is doesn't help.

I cannot really answer based on a simple image, but from my previous experience, setting shadow offset to the required height and width should do the trick for the iOS.

Read more about it here: Shadow Offset

Here's a picture of what my card looks like with the following style used:

marginLeft: 10,
    backgroundColor: 'white',
    shadowColor: 'blue',
    alignItems: 'center',
    shadowOffset: {width: 3, height: 3 },
    shadowOpacity: 1.0,
    borderRadius: 10,

My card View

Hope it works out well for you.

Display custom shadow color >= 28 or >= P for above Sdk level 28

enter image description here

Code

<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
  <View
    style={{
      shadowColor: 'purple',
      height: 150,
      width: '90%',
      backgroundColor: 'white',
      alignItems: 'center',
      justifyContent: 'center',
      //android specific
      elevation: 10,
      //ios specific
      shadowOffset: { width: 1, height: 1 },
      shadowRadius: 3,
      shadowOpacity: 0.5,
    }}>
    <Text style={{ color: 'rgba(128,0,128,0.5)' }}>
      Welcome to React Native
    </Text>
  </View>
</View>

In android we can adjust shadow by elevation property

In iOS we can adjust shadow by shadowOffset, shadowRadius,shadowOpacity property

Output android

enter image description here

Output iOS

enter image description here

Available library for further usage

react-native-shadow-2 react-native-drop-shadow

Create a Shadow.js

export const Shadow = (elevation) => { // Receive elevation as a prop
  return {
    elevation,
    shadowColor: 'black',
    shadowOffset: { width: 0, height: 0.5 * elevation },
    shadowOpacity: 0.3,
    shadowRadius: 0.8 * elevation,
  };
};

import Shadow.js to the page where you want to apply

import Shadow from './Shadow'  //path to Shadow.js

<View style={{Shadow(5)}}> // pass elevation as a prop to Shadow.js
</View>

if you want to use in styles

import Shadow from './Shadow'  //path to Shadow.js

<View style={styles.shadow}>
</View>

const styles = StyleSheet.create({
 shadow:{
    ...Shadow(5) //use spread operator
}
});
Related