I want to introduce a multilingual system. I have a function component that returns a translation of a specific element based on selected language (from Context API).
Everything works well until I put the translated element into the form (option value, placeholder, etc.) - then it appears as an [object object].
That's where 2 questions are born:
Is it possible to return this component as a something like string, which HTML forms would accept?
Is it possible to apply context consumer to pure JS function, so it does not return a React component, but a primitive value?
Translation component:
const Translation = ({ element }) => {
let translation;
return (
<LanguageConsumer>
{({ language }) => {
switch (language) {
case "pl":
translation = plTranslation;
break;
case "en":
translation = enTranslation;
break;
default:
translation = enTranslation;
}
return translation[element];
}}
</LanguageConsumer>
);
};
Example:
<option value="en">
<Translation element="globalLanguageEnglish" />
</option>
Thanks in advance for your help.
string
object correctly. You are most likely trying to render thecontext
object or something else. – Doblaconst ComponentToRender = 'MyComponent';
and using it would be like<ComponentToRender />
. So if you have conditional elements to render you can pass just the componentsstring
name and then render it – Introgressionconst Value = () => "value"
and pass it to input placeholder like<input type="text" placeholder={<Value />}
. :-( – CharlenacharleneValue
as afunction
instead of rendering it as acomponent
:<input type="text" placeholder={Value()} />
– LeekgreenFragment
?return (<React.Fragment>{translation[element]}</React.Fragment>)
; – Leekgreen