Categories
React Answers

How to specify null prop type in React?

Spread the love

Sometimes, we want to specify null prop type in React.

In this article, we’ll look at how to specify null prop type in React.

How to specify null prop type in React?

To specify null prop type in React, we can set null as the default prop value.

For instance, we write:

import React from "react";
import PropTypes from "prop-types";

const MyComponent = ({ item }) => {
  return item;
};

MyComponent.propTypes = {
  item: PropTypes.string.isRequired
};

MyComponent.defaultProps = {
  item: null
};

export default function App() {
  return (
    <div>
      <MyComponent item="foo" />
      <MyComponent />
    </div>
  );
}

We create the MyComponent component accepts the item prop.

We set item‘s type to be a string and is required.

And then we specify that its default value is null so it can be set to null when nothing is set for item.

As a result, we see ‘foo’ rendered on the screen since we set item to 'foo' in the first MyComponent instance.

Conclusion

To specify null prop type in React, we can set null as the default prop value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *