What is the best approach to handle Flow types for component props and getDerivedStateFromProps when the props are not the same

Having a Component with its props, an additional prop is added for getDerivedStateFromProps. The issue arises when setting the props with the additional one, throwing an error that the prop is not being used. Conversely, setting it without the extra prop causes an error indicating that a prop which does not exist in the component props cannot be included:

type Props = {|
  name: string,
|};

type StaticProps = {|
  ...Props,
  surname: string,
|};

type State = {|
  name: string,
  surname: string,
|};

export class Foo extends Component<Props, State> {
  state: State = {
    name: '',
    surname: '',
  };

  static getDerivedStateFromProps(props: StaticProps) {
    return { surname: props.surname };
  }

  render() {
    return (
      <div>
        <div>{this.props.name}</div>
        <div>{this.state.surname}</div>
      </div>
    );
  }
}

In this scenario, Flow type raises an error:

Cannot create 'Foo' element because property 'surname' is missing in  'Props' [1] but exists in props [2].Flow(InferError)
.

When using

Component<StaticProps, State>
, another error is triggered:
'surname' PropType is defined but prop is never usedeslint(react/no-unused-prop-types)

What would be the correct way to define the flow types for this situation?

Answer №1

As indicated by the error message, Props does not have an attribute named surname that you are trying to set initially. Therefore, you should update your type definition to include this attribute:

type Props = {
  name: string,
  surname?: string
};

Note: It seems unnecessary to use two different types for Props—Props initially used and StaticProps within getDerivedStateFromProps.

Edit: If you do not require all attributes defined in Props, you can make them optional by adding the ? symbol after the attribute's name.

Answer №2

Thanks to the assistance of @BoyWithSilverWings, I was able to resolve the issue by following his suggestion to specify the React version in the .eslintrc file. Simply add the following code snippet to your .eslintrc file:

"settings": {
  "react": {
    "version": "<your react version>" // 16.8.5
  }
}

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

What is the best way to structure an array for JSON transmission between Express/NodeJS and ReactJS?

I have a query similar to the one posted on POST array of objects to REST API. However, I need a different formatting for my answer. My dataresults array contains Objects like: [ { reviewID: 5, TextComment: 'lol2314'}, { reviewID: 4, TextC ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

Why is it beneficial to integrate a state management library in a server-rendered application?

While working with NextJS to serve a SSR application, I have come across recommendations to use a state management library. In my experience, I am accustomed to using a state management library for client-side rendered applications, but I am unsure of it ...

Is there a way for me to obtain a selection of 20 random items from this JSON data

When working with my JSON data using Myjson.slice(1, 20), I encountered a situation where I needed to extract only 20 items from a dataset that had a length of 2624. In the code snippet provided, I attempted to use the slice method but struggled to differe ...

Having trouble with pinning the expand column on the far left side of my Material React Table

I am utilizing the Material React Table to display my data in a tree-like structure. My requirement is to pin the expand column (used for collapsing or expanding rows) at the leftmost position, followed by pinning the tasks column. While I have successful ...

Refresh the screen after 10 seconds

Apologies if I'm not explaining this well in advance. I am looking to create a dynamic webpage using JavaScript that automatically updates every 10 seconds. Does anyone have an example code snippet for this? **Specifically, allow ...

A versatile multi-select jQuery widget featuring the ability to choose options within a specific opt

I am on the hunt for a cool jQuery tool that has the following characteristics: It enables you to create multiple groups, such as: Group 1 - Sub 1 1 - Sub 1 2 - Sub 1 3 Group 2 - Sub 2 1 Group 3 - Sub 3 1 - Sub 3 2 By clicking on Group 1, for instance, ...

Exploring Nextjs with server-side rendering and fetching data from

When utilizing the getServerSideProps function in Next.js to make a fetch request to my API, I encountered an issue where the origin header was coming back as undefined. This seems to be specific to requests made from the server in Next.js, as I am able ...

Issue with ThemeManager in Material UI & React: Constructor is not valid

Currently, I am integrating Material UI into a small React application, but I suspect that the tutorial I am following is outdated and relies on an older version of Material UI. The error _materialUi2.default.Styles.ThemeManager is not a constructor keeps ...

Import Information into Popup Window

When a user clicks on the "view" button, only the details of the corresponding challenge should be displayed: Currently, clicking on the "view" button loads all the challenges. This is because in my view-one-challenge.component.html, I have coded it as fo ...

Building a customizable class from scratch

I am currently working on developing configurable classes that come with default values, but allow for configuration changes if needed. The concept involves creating an instance of a class by calling its type specified in the static properties of the Test ...

What is the correct way to link an array with ngModel using ngFor loop in Angular?

Utilizing ngModel within an ngFor iteration to extract values from a single input field like this : <mat-card class="hours" > <table id="customers"> <thead > <th >Project</th> ...

trouble with react-table's default height and flexible design

I am facing an issue with my React table configuration. I have set up scrollable columns and header following a similar example here: https://codesandbox.io/s/kowzlm5jp7?file=/index.js:281-310 In the table styles, I have specified a height like this: ...

The React loader fails to function properly when used with nested routes

I'm currently working on my App.js file where I have defined all the routes for my application. I wanted to implement React-Router data loader functionality. import React from 'react' import { Routes, Route, Navigate, RouterProvider, createB ...

Preventing the compilation process from overwriting process.env variables in webpack: A step-by-step guide

Scenario I am currently working on developing AWS Lambda functions and compiling the code using webpack. After reading various articles, I have come to know that the process.env variables get automatically replaced during compilation. While this feature ...

No display of Tailwind updates on local server in Safari browser using NextJS and a Mac M1

For my personal project with NextJS, I am using Tailwind CSS, but I am experiencing frequent issues with updating styles. It seems like there is a 50/50 chance that Tailwind will apply the styles to the component properly, and sometimes I have to go throug ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...

Whenever I attempt to make changes to the React state, it always ends up getting reset

Currently, I am attempting to utilize Listbox provided by Headless UI in order to create a select dropdown menu for filtering purposes within my application. However, the issue I have encountered is that whenever I update my "selectedMake" state, it revert ...

Verifying the accuracy of a React Component in interpreting and displaying a path parameter

I have the following React/Typescript component that is functioning correctly. However, I am struggling to write a test using testing-library. My goal is to verify that it properly receives the level parameter and displays it on the page: import React from ...

Creating a changing text color using Material UI and React

How can one dynamically set the text color based on the background color of a component using Material-UI API? If component A has a light background, then the text should be dark. For component B with a black background, the text should be light. (I have ...