Search code examples
javascriptreactjsreact-nativeshadowcard

Shadow is spreading away in react native


I am working on a react native project. I want to provide shadow to view. But it was spreading away like this.

enter image description here

But what I want is:

enter image description here

I got the answer that I need to add background color here: https://taketo.site/solved And that actually solves my problem but only when I add background color from the stylesheet. But my problem is that I want to get the background color from props as everytime the view is rendered, it won't have the same bg color, it would be different. But when I try to provide bg color from props, it again gives shadow like in the first image. Here's my code:

component file:

import React from 'react';
import { View } from 'react-native';
import { styles } from './styles';

class ShadowCard extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <View
        style={[
          styles.card,
          {
            width: this.props.width,
            height: this.props.height,
            backgroundColor: this.props.backgroundColor,
          },
        ]}>
        {this.props.children}
      </View>
    );
  }
}

export default ShadowCard;

stylesheet file:

import { StyleSheet } from 'react-native';

export const styles = StyleSheet.create({
  card: {
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.5,
    shadowRadius: 2,
    elevation: 10,
    borderRadius: 12,
    margin: 12,
  },
});

So what should I do so that I can take the bg color from props and the shadow shows up like in second image?


Solution

  • You can probably do something like this -> Wrap your current cart View in another View with overflow hidden to prevent the shadow to show up above the box and then add some padding bottom to show the shadow underneath the box for android, and for ios, keep the shadowOffset as it currently is

    <View style={{ overflow: 'hidden', paddingBottom: 60 }}>
    <View
        style={{
            width: this.props.width,
            height: this.props.height,
            backgroundColor: this.props.backgroundColor,
            shadowOffset: { width: 2, height: 6 },
            shadowRadius: 6,
            shadowOpacity: 0.2,
            elevation: 15,
          }}>
        {this.props.children}
      </View>
      </View>