Home > OS >  JSON-like syntax type to React Component Properties Parameter
JSON-like syntax type to React Component Properties Parameter

Time:11-27

I am trying to figure out how to convert the following React function into a React component class:

import type { AppProps } from 'next/app'
import React from 'react';
import '../styles/styles.css';

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

export default MyApp;

Since I am working with strict TypeScript compiler settings, when I write:

class MyApp extends React.Component {
  override render() ...
}

...I must supply the template (generic parameter?) arguments to the component like:

class MyApp extends React.Component<MyPropertyType, MyStateType>

But I do not know how to convert this syntax { Component, pageProps }: AppProps to the React component parameter type.

I have never seen this syntax, which I think is saying a JSON object with fields of Component and pageProps and the object is type AppProps?

CodePudding user response:

this syntax [...] is saying [an] object with fields of Component and pageProps and the object is type AppProps?

You guessed absolutely right! This is destructuring assignment (here of a function parameter).

Therefore in your case, AppProps is the type for your class-based component as well:

class MyAppClass extends React.Component<AppProps> {
  override render() {
    const { Component, pageProps } = this.props
    return <Component {...pageProps} />
  }
}

Playground Link

  • Related