2

I am trying to setup a defaultProps for some field of an array of object prop.

interface IProps {
  steps: Array<{
    id: number | string
    route?: string
    label?: string
    completed?: boolean
    disabled?: boolean
    active?: boolean
  }>
}


class Stepper extends React.Component<IProps, {}> {
  static defaultProps: IProps = {
    steps: ???
  }
  render() {
    return <div></div>
  }
}

I tried to look up online but I couldn't find a way of setting defaultProps for my case.

I would like to set some default value only for completed, disabled and active and leave the other as they are.

Is there an easy way to do this ?

2
  • Probably, declare interface ISomeOfIProps with completed, disabled and active members. And define defaultProps: ISomeOfIProps? :) Commented Sep 24, 2018 at 14:00
  • I am a bit new in Typescript with React (coming from JS only), would you mind setting up an example for me ? I would greatly appreciate ! Commented Sep 24, 2018 at 14:03

1 Answer 1

3

I'd extract interface IStep, and split it into partial and complete one:

interface IPartialStep {
  completed?: boolean
  disabled?: boolean
  active?: boolean
}

interface IStep extends IPartialStep {
  id: number | string
  route?: string
  label?: string
};

So, now it's logical to use 2 components: Step list (Stepper) and Step Item (Step):

interface IProps {
  steps: Array<IStep>
}

class Stepper extends React.Component<IProps, {}> {
  // actually, default props are moved to Step
  // so this one probably not needed.
  static defaultProps: IProps = {
    steps: []
  }
  render() {
    return this.props.steps.map(step => <Step {...step}/>);
  }
}

class Step extends React.Component<IStep> {
  static defaultProps: IPartialStep = {
    // here you can define default props for step item
    completed: false,
    disabled: false,
    active: false,
  }
  render() {
    const {id, route, ...} = this.props;
    // here you define how to display every step
    return <div>{id}</div>
  }
}

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, this is exactly what I needed ! Now I know that I need to split my component when I come across case like this ! Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.