DEV Community

Randy Rivera
Randy Rivera

Posted on

Review Using Props with Stateless Functional Components

  • We've been passing props to stateless functional components. These components act like pure functions. They accept props as input and return the same view every time they are passed the same props.
  1. A stateless functional component is any function you write which accepts props and returns JSX.
  2. A stateless component, on the other hand, is a class that extends React.Component, but does not use internal state (covered in the next post).
  3. A stateful component is a class component that does maintain its own internal state. You may see stateful components referred to simply as components or React components.
  • FreeCodeCamp now shows us the code editor thas a CampSite component that renders a Camper component as a child. They want us to define the Camper component and assign it default props of { name: 'CamperBot' }. We can render any code that we want but it has to have a p element that includes only the name value that is passed in as a prop. We should define propTypes on the Camper component to require name to be provided as a prop and verify that it is of type string.
class CampSite extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <Camper/>
      </div>
    );
  }
};
{/* Change code below this line*/}
Enter fullscreen mode Exit fullscreen mode

Answer:

{/* Change code below this line*/}
const Camper = (props) => {
  return <p>{props.name}</p>
}
Camper.defaultProps = {name: 'CamperBot'}
Camper.propTypes = { name: PropTypes.string.isRequired}
Enter fullscreen mode Exit fullscreen mode

Larson, Q., 2019. Review Using Props with Stateless Functional Components. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/react/add-comments-in-jsx

Top comments (1)

Collapse
 
mrwensveen profile image
Matthijs Wensveen

Like "normal" components, functional components can be stateful as well through the use of hooks.