Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: how to apply shadow and borderRadius to a View?

Is there a way to apply a shadow AND a borderRadius to a View component, with the shadow following the rounded corners ?

Currently you have to set overflow: 'hidden' for borderRadius to work, but doing so removes the shadows.

It apparently is an old and known issue in React Native, likely not going to be fixed in the near future. A workaround was proposed in this issue, of superposing two Views but no code sample was given.

Can anybody give a code example of this proposed solution ? Will it follow the rounded corners (I doubt it) ?

Is there a package with some native binding voodoo doing the trick ?

Is there another solution ?

I already tried the solution from this question but it did not work for a View, the borderRadius prop does not work and triggers a warning advising to nest it in a style prop.

like image 400
deb0ch Avatar asked Jun 01 '18 22:06

deb0ch


2 Answers

You can make use of this tool to generate parameters to shadows for both android and iOS.

And the trick is to make two Views, one for shadow with transparent background, other for the Content itself, both of them with the same borderRadius so a basic card will look like this:

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

export default () => {

return (
 <View style={styles.cardShadow}>
  <View style={styles.cardContainer>
    <Text> Card Content </Text>
  </View>
 </View>
)
}

const styles = StyleSheet.create({
cardShadow: {
 borderRadius: 16,
 backgroundColor: 'transparent',
 shadowColor: '#000',
 shadowOffset: {
   width: 0,
   height: 1,
 },
 shadowOpacity: 0.22,
 shadowRadius: 2.22,
 elevation: 3,
},
cardContainer: {
 backgroundColor: '#fff',
 borderRadius: 16,
 overflow: 'hidden',
},
});

In essence this is what you need to make a View with shadow and rounded corners, you could add also some margin/padding and flexbox to make a nice floating card.

like image 94
Rayon Nunes Avatar answered Oct 16 '22 17:10

Rayon Nunes


Yeah this is what they meant by that:

const shadowsStyling = {
    width: 100,
    height: 100,
    borderRadius: 10,
    shadowColor: "#000000",
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 0
    }
}

<View styles={shadowsStyling}>
   <View styles={{width: '100%', height: '100%', borderRadius: 10, overflow: 'hidden'}} />
</View>
like image 41
Trevor Avatar answered Oct 16 '22 17:10

Trevor