'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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |