Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component.

To achieve this, I have detailed the following instructions in the interface of the parent class component's state.

// Parent.tsx

interface ParentState {
  /**
   * This stores any errors that occur during rendering.
   */
  errors: string[];
}

export function Parent extends React.Component<{}, ParentState> {
  // ...

  render () {
    return <Child errors={errors} />
  }
}

In a separate file, within the child component, I aim to have the ChildProps interface share the same information.

// Child.tsx

interface ChildProps {
  /**
   * How can the definition of `ParentState.errors` be utilized here?
   */
  errors: string[]
}

export function Child (props: ChildProps) {
  return <ul>{errors.map(error) => <li key={index}>error</li>}</ul>
}

I attempted using the JSDoc

@borrow module:Parent.ParentState.errors
tag while specifying @module Parent for the Parent component. But unfortunately, I am struggling to connect these two documentations. Despite my efforts, the documentation for the child prop does not appear in VSCode intellisense.

So, my query is: How can I borrow documentation from an external interface property?

Answer №1

@inheritdoc support is not available at the moment, but an alternative option is to utilize TypeScript instead of JSDoc. To achieve this, you can export your ParentState interface and import it as a type in the Child component like shown below:

// Parent.tsx
import * as React from "react";
import { Child } from "./Child";

export interface ParentState {
  /**
   * Stores the list of errors encountered during render.
   */
  errors: string[];
}

export class Parent extends React.Component<{}, ParentState> {
  state = {
    errors: [],
  };

  render() {
    return <Child errors={this.state.errors} />;
  }
}

// Child.tsx

import type { ParentState } from "./Parent";

interface ChildProps {
  errors: ParentState["errors"];
}

export function Child(props: ChildProps) {
  return (
    <ul>
      {props.errors.map((error, index) => (
        <li key={index}>{error}</li>
      ))}
    </ul>
  );
}

However, I suggest using a separate type that can be shared between the Parent and Child components as a more efficient solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with my Angular application, seems to be stuck at the loading screen. Not sure what's causing it, possibly

Hey there, I'm hoping to create a straightforward app that showcases posts. However, I've encountered an issue when deploying the initial page which is stuck on "Loading...". I believe it's a minor problem and would appreciate your assistan ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...

When attempting to connect to the MongoDB cloud, an unexpected error arises that was not present in previous attempts

npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650800170b4816001713001725544b554b55">[email protected]</a> start > nodemon index.js [nodemon] 3.0.2 [nodemon] to restart at any time, enter ...

Using TypeScript with React: Step-by-step guide to creating a ref prop

I'm currently using Ionic with React (typescript) and working on creating my custom form builder. Within this process, I've created a form that requires a ref property for referencing purposes when in use. My challenge lies in defining a prop tha ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

Utilizing React Ag Grid with custom Material design elements

Is it possible to apply material theme based classes to Ag Grid rows? Here is the scenario I am facing. Thank you in advance. Material Styles const customStyles = makeStyles((theme) => ({ actionIcon: { '& svg': { f ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Tips for selecting content for rendering with GetServerSideProps

Is there a way to display different text before and after a specific time without revealing all the content in the HTML? I've attempted using if-else logic within the component, but it ends up exposing text that should be hidden. Can getServerSideProp ...

Using React.js to create table cells with varying background colors

For my React application, I am working with a table that utilizes semantic ui. My goal is to modify the bgcolor based on a condition. In most cases, examples demonstrate something like bgcolor={(condition)?'red':'blue'}. However, I requ ...

Differences between Material UI's @mui/material/Button and @material-ui/core/Button: How has it evolved, and where can one find documentation for the previous

As I was looking to incorporate Material UI into my React project, a quick search led me to an article on Medium titled Getting Started With Material-UI For React. The video tutorial suggested using: npm install @material-ui/core It also recommended impor ...

I was caught off guard by the unusual way an event was used when I passed another parameter alongside it

One interesting thing I have is an event onClick that is defined in one place: <Button onClick={onClickAddTopics(e,dataid)} variant="fab" mini color="primary" aria-label="Add" className={classes.button}> <AddIcon /> & ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Obtaining the dimensions of each individual child component within an NgTemplate

I have the following code snippet within my template. While I can iterate through its components using `get`, it does not return an object that allows me to access deeper into the HTML attributes. <ng-template #container></ng-template> Compon ...

Learn how to connect a Firebase account that was created using a phone number

✅ I have successfully implemented the feature that allows users to update their profile with a mobile number using verifyPhoneNumber and update currentUser.updatePhoneNumber ❌ However, a problem arises when a new user attempts to sign in with a phone ...

Typescript types for the Google Calendar API

Is there anyone out there who can confirm whether the google Calendar API (via the npm package googleapis) for node.js or browser supports types that can be utilized in TypeScript? This would allow for a more strongly typed approach in projects using node ...

How to open a new tab in ReactJS

When attempting to open a component in a new tab using the Link in React router, it results in a 404 error page being displayed instead of the desired react component. The main React entry point file (js), import React from 'react'; import { re ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

The ReactDOM.createPortal modal has been successfully mounted onto the DOM, however, there seems to be no visible content

This project utilizes TypeScript and Next.js. Within it, there is a Modal component: interface ModalProps { onCancelModal: () => void; onAcceptModal: () => void; acceptEnabled: boolean; isLoading?: boolean; title: string; } const Modal: Re ...

Adding Google Ads to a page with changing content using Next.js and React

After fetching articles from an API, I proceed to parse the HTML code: function Article({ article }) { return ( <PageContainer> <div className={styles.container}> {parser(article.content.html)} ...