Search code examples
reactjsarrow-functions

Arrow Function in React not Evaluating when used as Children in Jsx


I am new to React and Js(x) so I started out with a Hello World Program using a class Person as a component having 2 attributes, a first and last name and printing.

class Person extends Component {
  constructor(props){
    super(props);
    this.firstName = "Amaze";
    this.lastName = "Name";
    if (this.props.firstName !== undefined){
      this.firstName = this.props.firstName;
    }
    if (this.props.lastName !== undefined){
      this.lastName = this.props.lastName;
    } 
    this.fullName = ()=>{"" + this.firstName + this.lastName};
    // ^ Above line prints the function as a string instead of 
    //   evaluating it and printing the fullName 
    console.log(this.fullName);
  }

  render() {
    return (
      // Get a warning in the dev tools and output as Hello <blank>
      <h1>Hello, { () => "" + this.firstName + " " + this.lastName }</h1>
    );
  }
}

Now, In the above code the render method is throwing out a function instead of a React component. Furthermore, the console log of this.fullName is printing the following:

ƒ () {
      "" + _this.firstName + _this.lastName;
    }

So, My Question is whether it possible to use an arrow function in the render similar to how I have used it. If yes, how?
I welcome a better solution (which is obviously out there) of printing the fullName on the fly.


Solution

  • Is this more what you're going for?

    class Person extends Component {
      constructor(props){
        super(props);
        this.firstName = "Amaze";
        this.lastName = "Name";
        if (this.props.firstName !== undefined){
          this.firstName = this.props.firstName;
        }
        if (this.props.lastName !== undefined){
          this.lastName = this.props.lastName;
        } 
        this.fullName = () => `${this.firstName} ${this.lastName}`;
        console.log(this.fullName());
      }
    
      render() {
        return <h1>Hello, { this.fullName() }</h1>;
      }
    }