i18next how to use the Trans component in React Native - react-native

How to apply a bold weight to certain parts of the translation using the Trans component in React Native?
Since HTML tags like <strong></strong> don't work, we have to create our own custom <Strong/> component that applies certain text styling to the translation, but I don't know how to do that despite reading the docs?

Docs:
import { Trans } from 'react-i18next';
function MyComponent({ person, messages }) {
const { name } = person;
const count = messages.length;
return (
<Trans i18nKey="userMessagesUnread" count={count}>
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>
);
}
i guess you can use <Text style={{fontWeight: 'bold'}}>{{name}}</Text> instead of <strong title={t('nameTitle')}>{{name}}</strong>.
or using useTranslation
import React from 'react';
import { useTranslation } from 'react-i18next';
export function MyComponent() {
const { t, i18n } = useTranslation();
// or const [t, i18n] = useTranslation();
return <Text style={{fontWeight: 'bold'}}>{t('my translated text')}</Text>
}
don't test yet

Related

Style React Native switch component

I'm developing a mobile application using React Native. This project needs a custom button to provides a boolean type of input. But I have no idea how to create this kind of custom component for that. I did a research and I try to create this custom button with a react-native switch (import { Switch } from 'react-native';). But seems like It is difficult to style.
I'm not sure what would be the best way to achieve that? Using the switch component? Please help me to find a better solution or new approach for this.
Thank you.
I have made a custom switch in react native and You can do the styling in it a source code is given below -
import React from 'react'
import { Text, TouchableOpacity } from 'react-native'
import styled from 'styled-components/native'
class App extends React.Component {
state = {
active: false
}
handleOFF = () => {
this.setState({
active: false
});
}
handleOn = () => {
this.setState({
active: true
});
}
render() {
return (
<MainView>
<Label>
<LabelOff onPress={this.handleOFF} active={this.state.active} activeOpacity={0.8}>
<Off>OFF</Off>
</LabelOff>
<LabelOn onPress={this.handleOn} active={this.state.active} activeOpacity={0.8}>
<On>ON</On>
</LabelOn>
</Label>
</MainView>
)
}
}
const MainView = styled.View`
margin:50px;
`
const Label = styled.View`
height:60px;
width:240px;
flex-direction:row;
justify-content:space-around;
align-items:center;
background-color:transparent;
`
const LabelOff = styled.TouchableOpacity`
height:60px;
width:120px;
background-color:${props => props.active ? 'transparent' : '#cb6161'};
border:2px solid #cb6161;
border-right-width:0px;
align-items:center;
justify-content:space-around;
`
const LabelOn = styled.TouchableOpacity`
height:60px;
width:120px;
background-color:${props => props.active ? '#55acee' : 'transparent'};
border:2px solid #55acee;
border-left-width:0px;
align-items:center;
justify-content:space-around;
`
const Off = styled.Text`
font-size:22px;
`
const On = styled.Text`
font-size:22px;
`
export default App
Custom switch is done !

How to render HTML in react-native

I am getting the html response from the api as shown below. I want to render the text and open the url on click of the text that is given in the response.
"Details": "<span style=\"font-family: Georgia; font-size: 24px;\"><em><span style=\"color: #0070c0;\">Click here to view News.</span></em></span>"
You can use WebView as HTML renderer like this,
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
class MyInlineWeb extends Component {
render() {
return (
<WebView
originWhitelist={['*']}
source={{ html: '<h1>Hello world</h1>' }}
/>
);
}
}
See official docs here
use this package react-native-render-html
extremely customizable and easy to use and aims at being able to render anything you throw at it.
import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';
const htmlContent = `
<h1>This HTML snippet is now rendered with native components !</h1>
<h2>Enjoy a webview-free and blazing fast application</h2>
<img src="https://i.imgur.com/dHLmxfO.jpg?2" />
<em style="textAlign: center;">Look at how happy this native cat is</em>
`;
export default class Demo extends Component {
render () {
return (
<ScrollView style={{ flex: 1 }}>
<HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
</ScrollView>
);
}
}

using multiple languages in a react native app

I have a react native app that I'm building as project for a company. the company wants to provide the option of choosing the language on set up and then changing it if needed from the settings page, same way the phone language on android works.
I first thought about saving the text in JSON file and loading the text from there when the app starts, and when I made my search I only found solution about localization rather than using multiple languages the way I'm doing.
So I was wondering if anyone can confirm that the JSON file solution I thought of is a good and useful idea and if there is other better solutions to use instead?
There are many solutions to this in react native. One would be to use i18n combined with your localization JSON files to create a multi language solution.
Example In Practice:
import React, { Component } from 'react';
import {
View,
Text
} from 'react-native';
import { strings } from '../locales/i18n';
class Screen extends Component {
render() {
return (
<View>
<Text>{strings('screenName.textName')}</Text>
</View>
);
}
}
Full Explanation: https://medium.com/#danielsternlicht/adding-localization-i18n-g11n-to-a-react-native-project-with-rtl-support-223f39a8e6f2
Project react-native-i18n is deprecated now. Read this article Internationalization in React Native which doesn't required any linking or any configuration except for this little configuration.
import i18n from 'i18n-js';
import en from './locales/en.json';
import de from './locales/de.json';
i18n.defaultLocale = 'en';
i18n.locale = 'en';
i18n.fallbacks = true;
i18n.translations = { en, de };
export default i18n;
To display internationalized information on the page we can use i18n.t() function by passing a translation key as an argument. e.g. i18n.t("home.welcome")
using multilanguage (HINDI,ENGLISH) in react native app
frist create 2 json file
main folder...Language
1..hi.json
{
name:'Name'
Address:'Address'
}
2..en.json
{
name:'नाम'
Address:'पता'
}
3.then install this... i18n
4..create a file i18n.js
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import en from '../Language/en.json';
import hi from '../Language/hi.json';
i18n.use(initReactI18next).init({
lng: 'en',
fallbackLng: 'en',
resources: {
en: en,
hi: hi,
},
interpolation: {
escapeValue: false
}
});
export default i18n;
5...App.js import this lines
import './Language/i18n';
import {useTranslation} from 'react-i18next';
6...App.js code
function HomeScreen() {
const {t,i18n} = useTranslation();
const [currentLanguage,setLanguage] =useState('en');
const changeLanguage = value => {
i18n
.changeLanguage(value)
.then(() => setLanguage(value))
.catch(err => console.log(err));
};
return (
<View style={{flex:1,backgroundColor:'#ccc'}}>
<Text>{t("name")}</Text>
<View>
<TouchableOpacity onPress={()=>changeLanguage('en')}>
<Text> ENGLISH</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>changeLanguage('hi')}>
<Text>हिन्दी</Text>
</TouchableOpacity>
</View>
</View>
);
}
export default HomeScreen;

Using a class as props in a react native component

I'm learning react (coming from a native iOS/Swift background) and I'm a bit confused about something I can't get to work.
I have a component that accepts props, so I figured I would write a class to model those props:
class HeaderProps {
text: string;
constructor(headerText:string) {
this.text = headerText;
}
}
// Make a component
const Header = (props:HeaderProps) => {
const { textStyle, viewStyle } = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{props.text}</Text>
</View>
);
};
and I'm exporting from my component like so:
export {Header, HeaderProps};
I'm then importing it:
import {Header, HeaderProps} from './src/components/header';
// Create a component
const App = () => ( <Header headerText={ new HeaderProps('Album') } />);
No text is appearing in my component.
If I just pass a string through as props it works fine, can't think of any reason why sending a class through wouldn't work.
I'm using flow type to declare the types of my arguments, not sure if that might be causing any issues.
A point in the right direction would be much appreciated!

Font loading error when using the ShoutemUI/TextInput component in a Exponent react-native framework

I'm trying to use shoutem/ui with exponent and I’m getting an error using the shoutem/ui textinput component, where I get the following error message fontFamily Rubik is not a system font and has not been loaded through Exponent.Font.loadAsync
However I loaded all the custom shoutem fonts that were listed in the blog post https://blog.getexponent.com/using-react-native-ui-toolkits-with-exponent-3993434caf66#.iyiwjpwgu
Using the Exponent.Font.loadAsync method.
fonts: [
FontAwesome.font,
{'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf')},
{'Rubik-Black': require('./node_modules/#shoutem/ui/fonts/Rubik-Black.ttf')},
{'Rubik-BlackItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-BlackItalic.ttf')},
{'Rubik-Bold': require('./node_modules/#shoutem/ui/fonts/Rubik-Bold.ttf')},
{'Rubik-BoldItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-BoldItalic.ttf')},
{'Rubik-Italic': require('./node_modules/#shoutem/ui/fonts/Rubik-Italic.ttf')},
{'Rubik-Light': require('./node_modules/#shoutem/ui/fonts/Rubik-Light.ttf')},
{'Rubik-LightItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-LightItalic.ttf')},
{'Rubik-Medium': require('./node_modules/#shoutem/ui/fonts/Rubik-Medium.ttf')},
{'Rubik-MediumItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-MediumItalic.ttf')},
{'Rubik-Regular': require('./node_modules/#shoutem/ui/fonts/Rubik-Regular.ttf')},
{'rubicon-icon-font': require('./node_modules/#shoutem/ui/fonts/rubicon-icon-font.ttf')},
],
});
Looking through the code I couldn't find the obvious fix - had trouble even finding where the style was set to throw the error.
The code above seem to be missing one line. Try adding this line to the array list:
{'Rubik': require('./node_modules/#shoutem/ui/fonts/Rubik-Regular.ttf')}
Use this code from the link
import React, { Component } from 'react';
import { StatusBar } from 'react-native';
import { Font, AppLoading } from 'expo';
import { View, Examples } from '#shoutem/ui';
export default class App extends React.Component {
state = {
fontsAreLoaded: false,
};
async componentWillMount() {
await Font.loadAsync({
'Rubik': require('./node_modules/#shoutem/ui/fonts/Rubik-Regular.ttf'),
'Rubik-Black': require('./node_modules/#shoutem/ui/fonts/Rubik-Black.ttf'),
'Rubik-BlackItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-BlackItalic.ttf'),
'Rubik-Bold': require('./node_modules/#shoutem/ui/fonts/Rubik-Bold.ttf'),
'Rubik-BoldItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-BoldItalic.ttf'),
'Rubik-Italic': require('./node_modules/#shoutem/ui/fonts/Rubik-Italic.ttf'),
'Rubik-Light': require('./node_modules/#shoutem/ui/fonts/Rubik-Light.ttf'),
'Rubik-LightItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-LightItalic.ttf'),
'Rubik-Medium': require('./node_modules/#shoutem/ui/fonts/Rubik-Medium.ttf'),
'Rubik-MediumItalic': require('./node_modules/#shoutem/ui/fonts/Rubik-MediumItalic.ttf'),
'Rubik-Regular': require('./node_modules/#shoutem/ui/fonts/Rubik-Regular.ttf'),
'rubicon-icon-font': require('./node_modules/#shoutem/ui/fonts/rubicon-icon-font.ttf'),
});
this.setState({ fontsAreLoaded: true });
}
render() {
if (!this.state.fontsAreLoaded) {
return <AppLoading />;
}
return (
<View styleName="flexible">
<Examples />
<StatusBar barStyle="default" hidden={false} />
</View>
);
}
}