DEV Community

h-mitchy
h-mitchy

Posted on

How to properly set up box-shadow with styled-components in ReactNative: full explanation with 3 examples

When styling in ReactNative, you can often use styled-components to create beautiful, concise designs. However, setting up box-shadow can be a bit tricky.

This article will walk you through three examples (two failures and one success) of how to use styled-components to set up box-shadow in a ReactNative project.

Failure #1: General box-shadow specification

ReactNative does not allow you to specify box-shadow directly like general CSS.

import styled from 'styled-components/native';

export const Container = styled.View`
width: 150px;
height: 52px;
border-radius: 26px;
backgroundColor: "#FFFFFF";

//shadow
box-shadow: 2px 8px 12px rgba(0, 0, 0, 0.16);
`;
Enter fullscreen mode Exit fullscreen mode

Writing it this way does not reflect the shadow.

Failure #2: Wrong writing of shadow-offset

In ReactNative, properties such as shadow-color, shadow-opacity, shadow-radius, and shadow-offset are used to set shadows. However, if you specify shadow-offset with an object, as shown below, it will not be reflected.

import styled from 'styled-components/native';
import { Platform } from 'react-native';

export const Container = styled.View`
width: 150px;
height: 52px;
border-radius: 26px;
backgroundColor: "#FFFFFF";

//shadow
shadow-color: "#000000";
shadow-opacity: 0.16;
shadow-radius: 12px;
shadow-offset: {
width: 2px;
height: 8px;
};
${Platform.OS === 'android' && `elevation: 6;`}
`;
Enter fullscreen mode Exit fullscreen mode

Success example: Correct way to write `shadow-offset

The correct way to write shadow-offset is as follows.

`jsx
import styled from 'styled-components/native';
import { Platform } from 'react-native';

export const Container = styled.View`
width: 150px;
height: 52px;
border-radius: 26px;
backgroundColor: "#FFFFFF";

//shadow
shadow-color: "#000000";
shadow-opacity: 0.16;
shadow-radius: 12px;
shadow-offset: 2px 8px;
${Platform.OS === 'android' && elevation: 6;}
;

Specifying this way will correctly reflect the shadow.

Summary

When specifying box-shadow in ReactNative using styled-components, you need to be careful how to write shadow-offset. By mastering the correct way to write it, you can add beautiful shadow effects to your application. We hope this article will help you to proceed smoothly with your development.

Top comments (0)