React-Router-Dom을 React Native에서 사용하기 (React-Router-Native)
react에서 아마 가장 많이 사용되는 라우팅 라이브러리는 react-router-dom이다.
react native에서는 라우팅을 위해서 react-navigation을 많이 사용하지만, react router dom을 사용하고자 한다면 react router native를 사용할 수 있다.
🍅 react router native의 기본적인 사용법은 다음과 같다.
import React from 'react';
import {Text, SafeAreaView} from 'react-native';
import {NativeRouter, Route, Routes} from 'react-router-native';
import Landing from './screens/Landing';
function App() {
return (
<NativeRouter>
<Routes>
<Route element={<Landing />} path="/" />
<Route
element={
<SafeAreaView>
<Text>About As</Text>
</SafeAreaView>
}
path="/about"
/>
</Routes>
</NativeRouter>
);
}
export default App;
사용법은 react router dom과 크게 다르지 않으므로, 기존에 리액트 개발자라면 쉽게 사용할 수 있다.
🍊 페이지간의 이동을 위해서는 Link 컴포넌트를 사용한다.
import React from 'react';
import {Text, SafeAreaView} from 'react-native';
import {Link} from 'react-router-native';
export default function Landing() {
return (
<SafeAreaView>
<Link to="/about">
<Text>GO ABOUT LINK</Text>
</Link>
</SafeAreaView>
);
}
Link 태그 내부에는 Text 등 다른 요소가 들어가야 한다.
Link 내부의 컴포넌트가 화면에 렌더링되고, 해당 요소를 클릭하면 연결된 스크린으로 이동할 수 있다.
🍓 페이지를 이동하며 상태를 전달할 수도 있다.
import React from 'react';
import {Text, SafeAreaView, StyleSheet, View} from 'react-native';
import {Link} from 'react-router-native';
export default function About() {
return (
<SafeAreaView style={styles.container}>
<Text>About As</Text>
<Link
to="/dummy"
state={{
name: 'Park',
age: 42,
}}>
<Text>dummy go</Text>
</Link>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
});
Link의 state props를 전달하면, 상태값을 전달할 수 있다.
전달받은 상태값은 useLocation 훅을 통해서 확인할 수 있다.
import React from 'react';
import {SafeAreaView, Text} from 'react-native';
import {useLocation} from 'react-router-native';
export default function Dummy() {
const location = useLocation();
console.log('location.state', location.state);
return (
<SafeAreaView>
<Text>
Dummy {location.state.name} {location.state.age}
</Text>
</SafeAreaView>
);
}
🍒 참고 문서
https://reactrouter.com/en/main/router-components/native-router
NativeRouter v6.11.1
Type declarationdeclare function NativeRouter( props: NativeRouterProps ): React.ReactElement; interface NativeRouterProps extends MemoryRouterProps {} is the recommended interface for running React Router in a React Native app. defaults to ["/"] (a single
reactrouter.com
https://reactrouter.com/en/main/components/link-native
Link (RN) v6.11.1
(React Native) This is the React Native version of . For the web version, go here. Type declarationdeclare function Link(props: LinkProps): React.ReactElement; interface LinkProps extends TouchableHighlightProps { children?: React.ReactNode; onPress?(event
reactrouter.com