All the solutions given here are correct.
The easiest change is to just wrap your function call in a JSX element:
return (
<div>
{ this.renderRecipeItems() }
</div>
)
However, none of the answers are (correctly) telling you why the code was breaking in the first place.
For the sake of an easier example, let’s simplify your code a bit
// let's simplify this
return (
{ this.renderRecipeItems() }
)
such that the meaning and behavior are still the same. (remove parenths and move curlies):
// into this
return {
this.renderRecipeItems()
};
What this code does is it contains a block, denoted by {}
, within which you’re trying to invoke a function.
Because of the return
statement, the block {}
is treated like an object literal
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).
which expects either a: b
or a
(shorthand) syntax for it’s property-value pairs.
// valid object
return {
prop: 5
}
// also valid object
const prop = 5;
return {
prop
}
However, you’re passing a function call instead, which is invalid.
return {
this.renderRecipeItems() // There's no property:value pair here
}
When going through this code, the engine assumes it will read an object-literal. When it reaches the this.
, it notices that .
is not a valid character for a property name (unless you were wrapping it in a string – see bellow) and the execution breaks here.
function test() {
return {
this.whatever()
// ^ this is invalid object-literal syntax
}
}
test();
For demonstration, if you wrapped your function call in quotes, code would accept the .
as part of a property name and would break now because a property value is not provided:
function test() {
return {
'this.whatever()' // <-- missing the value so the `}` bellow is an unexpected token
}
}
test();
If you remove the return
statement, the code wouldn’t break because that would then just be a function call within a block:
function test() {
/* return */ {
console.log('this is valid')
}
}
test();
Now, an additional issue is that it’s not the JS engine that is compiling your code but it’s babel, which is why you get the this is a reserved word
error instead of Uncaught SyntaxError: Unexpected token .
.
The reason is that JSX doesn’t accept reserved words from the JavaScript language such as class
and this
. If you remove this
, you can see that the reasoning above still applies – babel tries to parse the code as an object literal that has a property, but no value, meaning babel sees this:
return {
'renderRecipeItems()' // <-- notice the quotes. Babel throws the unexpected token error
}