I am attempting to implement a multi-language option in my React Native application. I'm using react-router
to navigate the page. The approach I am attempting involves passing the current locale to the components as a prop.
App.js
import React from 'react';
import {NativeRouter, Switch, Route} from 'react-router-native'
import WelcomePage from './components/WelcomePage'
import TestPage from './components/TestPage'
let lang = 'en'
const Main = () => {
return (
<NativeRouter>
<Switch>
<Route exact path="/" render ={() => <WelcomePage lang={lang}/>}/>
<Route exact path="/testpage" render{() => <TestPage lang={lang}/>}/>
</Switch>
</NativeRouter>
)
}
export default Main;
WelcomePage.js
import React from 'react'
import {Text, View, Button} from 'react-native'
const WelcomePage = ({history, lang}) => {
return (
<View>
<View>
<Text>Current language: {lang}</Text>
{// works so far}
</View>
<View>
<Button title="Change view" onPress={() => history.push("/testpage")}/>
{//crashes here, assumably because it doesn't get the history prop through the render() function}
</View>
</View>
)
}
export default WelcomePage
This seems to work for the most part, but crashes on history.push()
, with the error message
undefined is not an object (evaluating 'history.push')
From this it seems apparent to me that it is not possible to access the history
prop in this scenario, but why is that? And how can I fix my issue? Perhaps my fundamental approach is flawed, in which case I would appreciate any suggestions for improvements. Thank you.