a blog for those who code

Monday, 7 January 2019

How to Solve - Syntax Error: this is a reserved word in render() function in React.js

When starting with React.js you might encounter the error Syntax Error: this is a reserved word in render() function, what does this mean, how to solve the error and what should you do to not get this error again.


For Example: Let's say you are creating a list of Fake Users from Faker in React, so what you will do is write a buildFakeUser function to return you the name, avatar and email whereas fakeUsers to get the number of fake users you want as shown below :

buildFakeUser() {
 return {
  name: faker.internet.userName(),
  avatar: faker.internet.avatar(),
  email: faker.internet.email()
 };
}
fakeUsers() {
 for(var i = 0; i < 5; i++) {
  this.users.push(this.buildFakeUser())
 }
}

Now when you try to render the component the first thing you will do it to call the fakeUsers function as shown below :

render() {
  return (
    {this.fakeUsers()}
  );
}

Now the above code will give you an error as Syntax Error: this is a reserved word in render() function in React.js. This is because whatever is inside the return function is treated as an object literal. Now when we are passing "this.fakeUsers()", the engine notices a dot (.) which is not a valid character for a property name thus the execution breaks here.

Now how to fix this error, the simple way to fix this is to wrap your function call in a JSX element as shown below

render() {
  return (
    <div>
     {this.fakeUsers()}
    </div>
  );
}

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a comment