The useTranslator() hook provides access to the underlying translate method, but you really shouldn’t be using it very often. However, it is helpful in niche situations where you need to translate text on the fly (outside of standard component text or hooks).
To use it, simply call the hook and extract the translate method. Then, you can call the translate method wherever you like in your code (such as in an effect).
It can be useful in scenarios where you need finer grain control over translations, but most scenarios can be addressed via the useTranslation() hook.
Its first argument should be the string you’d like to translate. You can also provide additional options as the second argument to adjust how translations are handled (the same way you can control translations in the <TranslatedText /> component).
Copy
import { useTranslator } from '@lexiconjs/react'import { Alert } from 'react-native'import React, { useEffect } from 'react'export const useMyNicheHook = () => { // Grab the underlying translate function const { translate } = useTranslator(); useEffect(() => { // Make some kind of call that returns a string const untranslatedString = retrieveString(); // Translate that string and show an alert translate(untranslatedString) .then(({ translation }) => { Alert.alert(translation) }) .catch((err) => { console.error('Failed to translate', err) }) }, [])}
Keep in mind that this method is asynchronous and returns a promise.
Any additional context/guidance that you would like to provide to the translator.
This is most commonly used when you are translating a single word that can be interpreted multiple different ways. However, it can also be useful if you want to slightly tweak how translations are being generated.
For example, you can provide the context “Track my progress” when the child string is “Track”.
The locale we would like to translate the text to.
You should almost never provide this prop because it is set based on the targetLanguage prop provided to the <TranslationProvider /> (which defaults to the user’s detected locale).