Using Props with Stateless Functional Components: Why Use Class not Const?

Using Props with Stateless Functional Components: Why Use Class not Const?
0

#1

So I got this one to work, but I’m curious about why my first attempt (below) failed:

Your code so far


class CampSite extends React.Component {
    constructor(props) {
      super(props);
    }
    render() {
      return (
        <div>
          <Camper />
        </div>
      );
    }
  };
  // change code below this line
  const Camper = () => {
    return (
      <p>{this.props.name}</p>
    );
  };
  
  Camper.defaultProps = { name: 'CamperBot' };
  
  Camper.propTypes = {name: PropTypes.string.isRequired}


Here, I’m creating Camper as a variable, not as a class. I’m just curious if someone could elaborate on the difference in react between classes and variables, so I could get a better idea of why we need Camper to be a class in this instance.

Thanks!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/review-using-props-with-stateless-functional-components


#2

A class has an internal state. So using a class (in any language) implies that you’re creating an instance of an object, and you can call methods on that object to change the state.

A function takes some input and returns some output. It has no state. You give the function some data, it does something with the data, returns something back, then it’s done.

In your failing code, you aren’t passing anything to the function - this.props.name doesn’t exist because you haven’t passed it to the function. React isn’t special with regards to this, it’s the same in any programming language, or in maths, or whatever.

const Camper = (props) => {
  return (
      <p>{props.name}</p>
    );
};

That will work in most cases, because it’s now being passed something (an object I’m calling props that has a property name set on it).

However, in this case, Camper is supposed to be an object with a property called defaultProps. The function you’ve defined as Camper is a function, it isn’t an object.


#3

Thanks! This makes more sense to me.