Member-only story
React: Simple translation from scratch
React translation must be simple. Here I provide the simplest solution for React without using a 3rd party library.
1. Create a component and functions
It provides one component and translate functions
<T>
: Translation component. Usage<T>translate this</T>
t()
: Translate function. Usaget(`translate this`)
lang
: Get the current language. Usagelang
toggle()
: Toggle the current language. Usagetoggle()
date()
: Date translate function. Usagedate('2024-09-23')
The code for this file is provided later with a demo.
2. That’s it, import and use it
import { T, t, lang, toggle, date } from './Translation';
function App() {
return (
<>
<T>Current laguage</T>: {lang}
<button onClick={toggle}>Toggle language</button>
<div><T>Hello World</T></div>
<div>{t('Translation with a function t()')}</div>
<div><T>Translation not provided</T></div>
<div>{date(new Date)} Allen Kim</div>
</>
)
}
export default App