Home > OS >  How to set class default props in react 18.2.0?
How to set class default props in react 18.2.0?

Time:12-20

I saw some news about defaultProps being deprecated, but altenate solution I found was targeting function like component. But what about class component? I am new to react. Feeling like so many react things has change these years.

Oh I saw a another way is to use a deprecated package Prop-types, but it just don't feel right.

image here

CodePudding user response:

Just use the static defaultProps property

Typescript example

class MyComponent extends React.Component<MyPropType,MyStateType> {

  static defaultProps = {
    /* Declare your default Props here */
  };

Javascript example

class MyComponent extends React.Component {
  render() {
    // ...implement render method
  }
}

// Set default props
MyComponent.defaultProps = {
  /* Declare your default Props here */
};

CodePudding user response:

yup, it will be deprecated in the future but only for functional components, for class-based components, it will stay as it is

  • Related