1

How can I set the default values of properties in React components when using with Typescript?

I saw from another question on SE that I could declare a static class variable of defaultProps as an object with its keys my properties, but this doesn't seem to work for me.

Somehow, the static variable defaultProps wasn't called from anywhere and the properties still don't have their default values.

Community
  • 1
  • 1
Carven
  • 14,988
  • 29
  • 118
  • 161
  • 2
    Can we have your [mcve](http://stackoverflow.com/help/mcve)? :) – Alex Aug 06 '16 at 08:19
  • 2
    Could you provide some code? Defining `defaultProps` as static class variable is works for me. – 1ven Aug 06 '16 at 14:47
  • Possible duplicate of [Default property value in React component using TypeScript](http://stackoverflow.com/questions/37282159/default-property-value-in-react-component-using-typescript) – mixel Oct 07 '16 at 11:34

1 Answers1

-1

Here's how I do it in the constructor:

interface iProps {
   value?: any;
   disabled?: boolean;
}

export class MyComponent extends React.Component<iProps, {}> {
   private value: any;
   private disabled: boolean;

   constructor(props: iProps) {
      super(props);

      var value: any = "";
      if (typeof this.props.value !== "undefined") {
         value = this.props.value;
      }

      var disabled: boolean = false;
      if (this.props.disabled) {
         disabled = true;
      }
   }

   handleClick(event) {
      //Bla bla bla
   }

   render() {
      return (
         <div>
            <button onClick={this.handleClick.bind(this) } disabled={this.disabled}>
               my button
            </button>
         </div>
      );
   } //end render.

   componentDidMount() {
      //Bla bla bla
   }

   componentDidUpdate() {
      //Bla bla bla
   }
} //end class.
Lambert
  • 2,233
  • 5
  • 29
  • 44
  • This code will not work if you first render MyComponent with disabled=true and then remove the prop in the next render. – mthurlin Jan 17 '17 at 10:59