Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and JSDoc - How to document a React component properly?

I am documenting my React Native components, but I don't know how to do it properly.

For the documentation generation, I am using jsdoc/better-docs, which is supposedly able to collect the comments you leave on your PropTypes and include them in the documentation. But... due to incompatibility issues, it is not possible to carry out this strategy in React Native, and, therefore, the PropTypes are not included in the documentation.

How do you document this React component using JSDOC?

/**
 * ??
 */
function Cat({ name, color = "#000" }) {
  return <View />;
}

Cat.propTypes = {
  name: PropTypes.string.isRequired,
  color: PropTypes.string,
};

I was doing the following:

/**
 * The cat properties.
 *
 * @typedef {object} Props
 * @property {string} name - The cat name.
 * @property {string} [color="#000"] - The cat color.
 */

/**
 * Cat component.
 *
 * @type {React.FC<Props>}
 * @returns {React.ReactElement} The cat.
 */
function Cat({ name, color = "#000" }) {
  return <View />;
}

Cat.propTypes = {
  /** The cat name. */
  name: PropTypes.string.isRequired,

  /** The cat color. */
  color: PropTypes.string,
};

But I am feeling that prop-types is useless after adding the type definitions (?).

How do you document your react components?

like image 603
Victor Molina Avatar asked May 23 '26 14:05

Victor Molina


1 Answers

The way to go is to use InferProps from prop-types. This method is only available for TypeScript :( and I am not using it... instead, I am combining JSDoc and PropTypes in my project to get some "typescript behaviors" in the development experience and auto-generate my documentation.

BUT THERE IS A WORKAROUND WITHOUT TYPESCRIPT

Just configure your JSDoc as I described here: JSDoc - reusing type definitions error (cannot find name ‘type name’)

Now, in your code, just do the following:

components/cat/propTypes.js:

...

export const CatPropTypes = {
   /** The cat data. */
   data: CatDataShape,
   /** The cat name. */
   name: PropTypes.string.isRequired,
   /** The cat color. */
   color: PropTypes.string,
};

components/cat/Cat.js:

import React from "react";
import { View } from "react-native";
import { InferProps } from "prop-types";

import { CatPropTypes } from "./propTypes"; // <-----

/**
 * Cat component.
 *
 * @type {React.FC<InferProps<import("./propTypes").CatPropTypes>>} <---- JSDoc is in TypeScript mode! FANTASTIC! :D
 * @returns {React.ReactElement} The cat.
 */
function Cat({ name, color = "#000" }) {
  return <View />;
}

Cat.propTypes = CatPropTypes; // <-----

Now everything is working like a charm and there is no reason to maintain useless JSDoc typedefs! :DDDDDD

like image 185
Victor Molina Avatar answered May 26 '26 04:05

Victor Molina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!