Home > Software design >  How to properly document the Props parameter of a React component when using Destructuring assignmen
How to properly document the Props parameter of a React component when using Destructuring assignmen

Time:09-27

I am trying to write the JSDocs for a React component that uses destructuring assignment to get the props as follows.

const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... }

The problem I have is that JSDocs expects to have one @param since PostComponent only accepts one component, but I'd like to document title and body as parameters of the component.

If I try to include them as parameters VScode shows a warning as expected:

/**
 * @component
 * @param {string} title the title of the post
 * @param {string} body the body of the post
 */
const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... }

If I document each parameter in the IPostComponent interface, the documentation is shown when hovering over the fields, but it is not included in the component documentation

interface eIPostComponent {
  /** The title of the post */
  title: string;
  /** The body of the post */
  body: string;
}

What is the preferred way to include JSDocs for this component?

CodePudding user response:

With JSDocs we can write a vivid description of our code snippets (functions, components, objects, methods etc) and Typescript interfaces and types provide a guarding skeleton that our code needs to follow so that we don't run into inexplicable typecasting errors.

Instead of documenting Interfaces and Types, I generally give them descriptive names and in the README.md file (for example) I mention where that particular interface will be used.

If I were to go a bit further, I'd just write a brief description comment before the interface definition. I think that's a clean way of doing it.

CodePudding user response:

Your function accepts only one parameter - an object.
You can document it while referencing it in the doc:

/**
 * @component
 * @param {obj} wrapping object
 * @param {string} obj.title title the title of the post
 * @param {string} obj.body the body of the post
 */
const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } 
  • Related