Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the scenarios one should use isRequired for PropType vs defaultProps in React Application

I constantly struggle to understand, when exactly should I be using .isRequired vs .defaultProps={...} My thought is that, I think I should never ever really need to use isRequired, because it seems manually creating a bug that can break in the application because create isRequired automatically remove the need to add a corresponding default prop, that makes me feel uncomfortable just because it means I won't be able to expect a fail-safe value.

It definitely sounds an opinion based question, but I look for a better opinion that makes more sense if there is one.

like image 608
Ezeewei Avatar asked Mar 06 '18 15:03

Ezeewei


People also ask

What is PropTypes and defaultProps in React?

createClass. In this version, the propTypes property is an Object in which we can declare the type for each prop. The getDefaultProps property is a function that returns an Object to create the initial props.

What is isRequired in React?

isRequired means that props element defined is required to be passed from parent component. If you don't pass it, React will give you a warning message.

Why do we need PropTypes in React?

PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.

Can we use PropTypes in functional component?

Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.


1 Answers

Using prop types is a good way of documenting the API for a component, so that other people know how it works without reading the code.

The way it's usually thought of is the component is guaranteed to render without errors if all the required props are supplied. The props that are not required would only enhance the component with additional functionality.

Consider this example

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      {avatarUrl && <img src={avatarUrl} />}
    </div>
  );
}

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  avatarUrl: PropTypes.string
};

Now, if you want to render a default profile picture if it's not supplied, you could remove the conditional check inside the component and provide a default value instead.

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      <img src={avatarUrl} />
    </div>
  );
}

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  avatarUrl: PropTypes.string
};

UserCard.defaultProps = {
  avatarUrl: "/assets/generic-picture.png"
};
like image 110
hampusohlsson Avatar answered Oct 14 '22 06:10

hampusohlsson