Reputation: 3270
How can I define a variable within JSX?
I've tried it with the following code but it doesn't work. No error is thrown, it just renders nothing.
const languages = {
en: {
language: "English"
},
de: {
language: "Deutsch"
}
}
{() => {
const { language: name } = languages[language]
return (
<>
{name}
</>
)
}}
Upvotes: 1
Views: 4324
Reputation: 722
Do you every render such component? Possible implementation of your component which should work is:
const languages = {
en: {
language: "English"
},
de: {
language: "Deutsch"
}
}
const LanguageComponent = ({language}) => {
const { language: name } = languages[language]
return (
<>
{name}
</>
)
}
Usage:
<LanguageComponent language='en' />
Upvotes: 4
Reputation: 21317
You're just defining the function
but never calling it. Either execute it immediately after declaration function(){return jsx}()
but the most common practice is to declare it outside jsx
's block
const renderItems = items => items.map(x => <Item key={x} />)
return <div>{renderItems()}</div>
Upvotes: 1
Reputation: 12691
You defined a function but did not call it, that's why it renders nothing :
{ () => {/* your code */} }
You can call the function inline like this :
{ (() => {/* your code */})() }
Or define it outside the render method for more readability
Upvotes: 3