끄적이는 개발노트
React Native - 스크린샷 활용 (2) 이미지 공유 (react-native-share) 본문
이번 글에서는 저번 스크린샷을 공유하는 기능을 알아본다.
react native에서는 자체적인 share 기능을 제공한다. 굉장히 간단하기 때문에 해당 기능을 처음에는 사용했었다. 하지만, 파일을 공유하기 위해서는 url을 넣어주어야 하는데 이는 ios에서만 지원하는 기능이다. 따라서, 별도의 라이브러리인 react-native-share를 활용한다.
https://www.npmjs.com/package/react-native-share
react-native-share
Social share, sending simple data to other apps.. Latest version: 12.0.9, last published: a day ago. Start using react-native-share in your project by running `npm i react-native-share`. There are 114 other projects in the npm registry using react-native-s
www.npmjs.com
1. 설치
npm install react-native-share
#or
yarn add react-native-share
2. 코드
// test.tsx
import CustomText from '@/components/text';
import {TestProps} from '@/types/stack';
import {useRef, useState} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import ViewShot from 'react-native-view-shot';
import Share from 'react-native-share';
const TestScreen = ({navigation}: TestProps) => {
const [uri, setUri] = useState<string>('');
const viewShotRef = useRef<ViewShot>(null);
const onCapture = async () => {
const viewShotUri = await viewShotRef.current?.capture?.();
if (viewShotUri) setUri(viewShotUri);
};
const onShareLink = async (uri: string, title: string, message?: string) => {
await Share.open({title, message, url: uri});
};
return (
<SafeAreaView className="flex-1">
<ViewShot
ref={viewShotRef}
style={style.viewShot}
options={{
fileName: `ScreenShot_${new Date().toDateString()}`,
format: 'jpg',
quality: 1,
}}>
<View className="w-2/3 h-2/3 flex justify-center items-center bg-white">
<CustomText className="text-success text-xl" children="테스트 화면" />
<Button title="캡처" onPress={onCapture} />
<Button
title="공유"
onPress={() =>
onShareLink(uri, '테스트 공유', '화면캡처 공유입니다.')
}
/>
</View>
</ViewShot>
</SafeAreaView>
);
};
export default TestScreen;
const style = StyleSheet.create({
viewShot: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'green',
},
});
정말 간단하게 캡처한 화면을 공유할 수 있다.
물론, 위의 공유 함수는 예시 코드로 title과 message, url만을 담고 있지만, 아래 공식문서를 통해 원하는 옵션들을 더 추가할 수 있다.
https://react-native-share.github.io/react-native-share/docs/share-open
Share.open | React Native Share
The open() method allows a user to share a premade message via a social medium they choose. In other words, code specifies the message that will be sent and the user chooses to whom and the social medium through which the message will be sent. This shared
react-native-share.github.io
3. 실행
'React Native' 카테고리의 다른 글
React Native - 헤더 버튼 추가 (0) | 2025.02.23 |
---|---|
React Native - 스크린샷 활용 (3) 갤러리 저장(@react-native-camera-roll/camera-roll) (0) | 2025.02.17 |
React Native - 스크린샷 활용 (1) 화면 캡처 (react-native-view-shot) (3) | 2025.02.17 |
React Native - 이미지 선택 (react-native-image-crop-picker) (0) | 2025.02.14 |
React Native - 이미지 선택 (react-native-image-picker) (0) | 2025.02.14 |