1252748
1252748

Reputation: 15370

Call method within render or use getter

When a render method should return a calculated value, is it more appropriate to use a class method

class User extends Component {
  getFullName () {
    const { fname, lname } = this.props
    return `${lname}, ${fname}`
  }
  render () {
    return <div>FULLNAME: {this.getFullName()}</div>
  }
}

or a getter:

class User extends Component {
  get fullName () {
    const { fname, lname } = this.props
    return `${lname}, ${fname}`
  }
  render () {
    return <div>FULLNAME: {this.fullName}</div>
  }
}

They both seem to work, but I'm unclear if calling a function within a render method is good practice or not and am curious if one is preferred over the other and why.

Upvotes: 2

Views: 1633

Answers (1)

jfriend00
jfriend00

Reputation: 707666

When a render method should return a calculated value, is it more appropriate to use a class method?

There's really no right or wrong here. It's just a matter of personal preference and coding style and what type of interface you prefer on your object.

If you want it to behave and seem to the caller like it's a property, then use a getter so the caller can access it like a property console.log(user.fullName).

If you want it to behave and seem to the caller like something that the object has to compute and return, then use a method (console.log(user.getFullName())`.

In this particular case, either is just fine. Since there's no setter, I'd personally probably use user.getFullName() myself so it's clear to the caller that this is something that can only be retrieved, not set and is probably a computed property, not something that is directly stored.

They both seem to work, but I'm unclear if calling a function within a render method is good practice or not and am curious if one is preferred over the other and why.

There's no issue at all with calling a function inside of render(). That's perfectly fine.

Upvotes: 2

Related Questions