StyleSheet
StyleSheet은 react native에서 기본적으로 제공되는 CSS 작성법이다.
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
const Home = () => {
return (
<View style={StyleSheet.compose(styles.container, StyleSheet.absoluteFill)}>
<Text style={[styles.innerText, styles.textColor]}>Hello World</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 12,
backgroundColor: 'gray',
},
innerText: {
fontSize: 30,
},
textColor: {
color: "red",
}
});
export default Home;
- StyleSheet.create를 통해서 객체를 생성하고 객체 내부에 프로퍼티로 컴포넌트에서 사용될 스타일을 지정한다.
- RN에서는 상위 컴포넌트의 스타일이 자식으로 상속되지 않으므로, 하위 Text에는 각각 스타일을 지정해주어야 한다.
- style props에 배열을 넣고, 그 안에 여러개의 스타일을 적용시킬 수도 있다. (배열 대신에 StyleSheet.compose() 메서드를 사용할 수도 있다)
- 배열 내부에서는 뒤에 적힌 스타일의 값이 앞의 스타일 값과 중복된다면, 덮어쓰기가 일어난다. 즉, 결과물은 뒤의 스타일이 적용된다.
- StyleSheet.absoluteFill, StyleSheet.absoluteFillObject, StyleSheet.hairlineWidth과 같이 StyleSheet이 기본적으로 제공하는 스타일도 있다.
- 별도로 라이브러리를 설치하지 않고 작성할 수 있는 RN의 기본적인 스타일 작성 방법이다.
Emotion
React에서도 사용되는 CSS-in-JS 라이브러리 emotion이다.
React native에서도 emotion을 사용할 수 있으며, 이를 통해서 styled component를 작성할 수 있다.
다음과 같이 필요한 라이브러리를 설치해준다.
npm install @emotion/react @emotion/native
https://emotion.sh/docs/@emotion/native
Emotion – @emotion/native
Style and render React Native components using emotion This package also depends on react, react-native and prop-types so make sure you've them installed. Use @emotion/react for theming support.
emotion.sh
공식 문서에서도 @emotion/native를 소개하고 있다.
import React from 'react';
import {View, Text} from 'react-native';
import styled from '@emotion/native';
const Home = () => {
return (
<ContainerView bc={'blue'}>
<InnerText>Hello World</InnerText>
</ContainerView>
)
}
const ContainerView = styled.View`
flex: 1;
padding: 12;
backgroundColor: gray;
border-width: 3px;
border-color: ${({bc}) => bc};
border-radius: 10px;
`
const InnerText = styled.Text`
text-align: center;
font-size: 12px;
color: red;
`;
export default Home;
- React에서 styled-component나 emotion을 사용해봤다면, 익숙할 것이다.
- React와는 다르게 HTML 태그가 아니라, RN의 컴포넌트를 사용하는 것이 다르다.
- ThemeProvider도 사용할 수 있으며, 이는 위의 공식문서를 참조하면 된다.
- props를 사용할 수 있어서 상태값에 따라서 조건부로 스타일링이 가능하다.
🧉 styled-components나 emotion은 Tagged templates 문법을 사용한다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates
Template literals (Template strings) - JavaScript | MDN
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
developer.mozilla.org
Tailwind (twrnc)
RN에서도 tailwind와 같이 클래스네임으로 스타일을 작성하려는 많은 라이브러리들이 생겼다.
그중에서도 최근에도 활발히 커밋이 일어나고 있는 라이브러리 중 하나인 twrnc를 소개한다.
twrnc는 Tailwind React Native Classnames의 줄임말로, RN에서 사용할 수 있는 tailwind 라이브러리이다.
https://tailwindcss.com/docs/text-color
Text Color - Tailwind CSS
Utilities for controlling the text color of an element.
tailwindcss.com
다만, 사용 가능한 classname이 명확히 나와있지 않은데, tailwind css 문서를 참조하여 예시를 작성하였다.
아마도 RN 환경에서도 기존의 tailwind css의 기능을 동일하게 사용하면 되는 것 같다 (twrnc는 tailwindcss 라이브러리에 대한 의존성이 설정되어 있다)
import React from 'react';
import {View, Text} from 'react-native';
import tw from 'twrnc';
const Home = () => {
return (
<View style={tw`bg-blue-100 ios:p-4 android:p-2`}>
<Text style={tw`text-black dark:text-white`}>Hello World</Text>
</View>
)
}
export default Home;
- 위와 같이 tw`` 으로 사용할 수 있다.
- 사용하기 간편하고, 클래스 이름으로 스타일을 유추할 수 있어 코드를 읽기 편한 장점이 있다.
- 플랫폼에 따른 스타일링, 다크모드, 미디어쿼리가 적용이 가능하다.
- 다만, 아직 다운로드 수가 적은 라이브러리로 emotion에 비해서는 상당히 적게 사용되고 있다.
- 개인적으로는 tailwind의 개발경험이 가장 좋았기 때문에 앞으로 더 발전이 되길 바란다.
twrnc에서 tailwind.config.js를 적용할 수 있는데, 방법은 다음과 같다.
import { create } from 'twrnc';
const tw = create(require('../tailwind.config.js'));
export { tw };
tailwind.config.js가 적용된 tw 함수를 생성하여 이를 사용하면 tailwind 설정이 적용된 채로 tailwind css를 작성할 수 있다.
🍪 React Native에서는 아직 독보적인 tailwind css 라이브러리가 정립되지 않은 것 같은데, 예를 들면 nativewind라는 라이브러리가 사실 twrnc보다는 더 많은 다운로드 횟수를 기록하고 있다.
🍪 twrnc를 소개한 이유는 twrnc를 사용한 오픈소스를 분석하는 중 이기도했고, 가장 최근에 업데이트가 된 react native의 tailwind css 라이브러리였기 때문이다.
🍪 또한, nativewind는 공식문서가 잘 구비되어 있으니, 그쪽을 참고하면 될 것 같다.
nativewind는 사용 방법이 twrnc와는 다른데, 공식 문서가 잘 되어있으니 참고하면 될 것 같다.
https://www.npmjs.com/package/twrnc
twrnc
simple, expressive API for tailwindcss + react-native. Latest version: 3.6.0, last published: 19 days ago. Start using twrnc in your project by running `npm i twrnc`. There are 18 other projects in the npm registry using twrnc.
www.npmjs.com
https://www.npmjs.com/package/nativewind
nativewind
Use Tailwindcss in your cross-platform React Native applications. Latest version: 2.0.11, last published: 4 months ago. Start using nativewind in your project by running `npm i nativewind`. There are 12 other projects in the npm registry using nativewind.
www.npmjs.com
Home | NativeWind
NativeWind uses Tailwind CSS as scripting language to create a universal style system for React Native. NativeWind components can be shared between platforms and will output their styles as CSS StyleSheet on web and StyleSheet.create for native.
www.nativewind.dev