
React Native 개발하면서 정말 많이 사용하게 되는 WebView에 대해 이야기해보려고 합니다.
WebView는 쉽게 말해서 앱 안에 있는 작은 브라우저라고 생각하면 됩니다. Chrome이나 Safari로 웹사이트를 보는 것처럼, 앱 안에서 웹 콘텐츠를 보여주는 컴포넌트입니다.
React Native에서는 원래 코어에 WebView가 포함되어 있었는데, 0.60 버전부터는 별도의 라이브러리로 분리. 그래서 지금은 react-native-webview라는 커뮤니티 라이브러리를 사용해야 합니다.
앱 스토어 심사 없이 즉시 업데이트 가능한 콘텐츠
자주 업데이트되는 콘텐츠
특정 기능만 웹으로 처리하고 싶을 때
하이브리드 앱 구조
성능이 중요한 기능
네이티브한 느낌이 중요할 때
# npm
npm install react-native-webview
# yarn
yarn add react-native-webview
# iOS 추가 설정 (iOS만)
cd ios && pod install
import React from 'react';
import { WebView } from 'react-native-webview';
const MyWebView = () => {
return (
<WebView
source={{ uri: 'https://your-website.com' }}
style={{ flex: 1 }}
/>
);
};
export default MyWebView;
//웹뷰 컴포넌트 적극 사용하기
import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';
const MyWebView = () => {
const webViewRef = useRef(null);
const sendDataToWeb = () => {
const data = { type: 'USER_INFO', name: '홍길동', age: 25 };
webViewRef.current?.postMessage(JSON.stringify(data));
};
return (
<WebView
ref={webViewRef}
source={{ uri: 'https://your-website.com' }}
onLoadEnd={sendDataToWeb} // 웹 로딩 완료 후 데이터 전송
/>
);
};
웹 쪽 코드:
// 웹에서 앱으로 메시지 보내기
const sendToApp = () => {
const data = { type: 'NAVIGATE', screen: 'home' };
window.ReactNativeWebView?.postMessage(JSON.stringify(data));
};
// 앱에서 온 메시지 받기
useEffect(() => {
const handleMessage = (event) => {
const data = JSON.parse(event.data);
console.log('앱에서 받은 데이터:', data);
};
// Android와 iOS 구분해서 이벤트 리스너 등록
const isAndroid = navigator.userAgent.includes('Android');
const eventType = isAndroid ? 'message' : 'message';
document.addEventListener(eventType, handleMessage);
return () => {
document.removeEventListener(eventType, handleMessage);
};
}, []);
앱 쪽 코드:
const handleWebViewMessage = (event) => {
const data = JSON.parse(event.nativeEvent.data);
if (data.type === 'NAVIGATE') {
// 특정 화면으로 이동
navigation.navigate(data.screen);
}
};
return (
<WebView
source={{ uri: 'https://your-website.com' }}
onMessage={handleWebViewMessage}
/>
);
WebView는 웹페이지를 로드해야 하니까 로딩 시간이 있다. 사용자가 빈 화면을 보지 않도록 로딩 인디케이터를 추가하기.
Android에서 하드웨어 뒤로가기 버튼을 눌렀을 때, 웹뷰 내에서 뒤로가기가 되도록 처리할 수 있다.
WebView는 네이티브 코드와 웹 코드가 함께 실행되면서 CPU 사용량과 메모리 사용량이 높아질 수 있다. 또한 배터리 소모도 네이티브 앱보다 많다.
WebView는 기본적으로 웹페이지를 로드해야 하니까 인터넷 연결이 필요. 오프라인 상황에 대한 대비책도 마련해두기.
외부 웹사이트를 로드할 때는 보안에 주의해야 한다. 신뢰할 수 있는 도메인만 허용하도록 설정하는 것이 좋다.
<WebView
source={{ uri: 'https://your-website.com' }}
originWhitelist={['https://your-website.com']}
mixedContentMode="never"
/>
iOS와 Android에서 WebView 동작이 조금씩 다를 수 있다.