Creating a language switcher component
If you have multiple locales and you want to add a way for your customers to select a language, currency, or location, you can implement a language switcher component.
In this example, we'll create a very basic component that's a dropdown selector to change the languages of our website.
- Create a Frontastic component schema
{
"tasticType": "language-switcher",
"name": "Language switcher",
"icon": "translate",
"schema": [
{
"label": "Show language switcher",
"field": "showLanguageSwitcher",
"type": "boolean",
"default": true
}
]
}
Then upload it to the Frontastic studio.
- Create a Frontastic component JSX file
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import app from '@frontastic/catwalk/src/js/app/app'
const LanguageSwitcher = ({ context, className }) => {
return (
<>
<select
className={`${className} uppercase`}
value={context.locale}
onChange={(event) => {
app.getLoader('context').refresh(
Object.assign({}, context.toParameters(), {
locale: event.target.value,
})
)
}}
>
{context.project.languages.map((language) => {
return (
<option value={language} key={language}>
{language.substring(0, 2)}
</option>
)
})}
</select>
</>
)
}
LanguageSwitcher.propTypes = {
context: PropTypes.object.isRequired,
className: PropTypes.string,
}
export default connect((globalState, props) => {
return {
context: globalState.app.context,
}
})(LanguageSwitcher)
The key method to change the language is:
app.getLoader('context').refresh(
Object.assign({}, context.toParameters(), {
locale: 'de_DE',
})
)
- Add to your
tastics.js
file
...
import languageSwitcherTastic from './language-switcher';
...
export default (() => {
return {
...
'language-switcher': languageSwitcher,
...
};
...
And that's it!
Updated over 1 year ago