0

i have an array which is defined in constants file as follows.

export const COMPLIANCE_CREATE_STEPS = [


    {
        name: 'Basic Info',
        component: BasicInfo,
        order: 1,
        // props: {
        //   handleChange: this.handleChange
        // }
      },
      {
        name: 'Company Rule Type',
        component: <CompanyRuleType />,
        order: 2
      }

  ]

I am rendering the components dynamically based on some condition. The code is as follows.

renderComponent() {
    let me = this;
    let step = constants.COMPLIANCE_CREATE_STEPS.filter(function (step, i) {
      return step.order == me.state.currentStep;
    });
    let Component = step[0].component;
    return (<Component />);
  }

Now I need to pass the props also from the constants file for each component.

If i remove the commented code from the constants file i am getting the following error.

Cannot read property 'handleChange' of undefined

When the component is rendered it should be something like

<BasicInfo handleChange={this.handleChange} />

How do i pass the prop method from constants file and use it in the dynamic component?

prajeesh
  • 1,610
  • 2
  • 24
  • 44

2 Answers2

1

You need a function to access component instance at runtime.

For example

export const COMPLIANCE_CREATE_STEPS = [
{
    name: 'Basic Info',
    component: BasicInfo,
    order: 1,
    props(parent) {
      return { handleChange: parent.handleChange.bind(parent), foo: 'bar' }
    }
  },
  {
    name: 'Company Rule Type',
    component: <CompanyRuleType />,
    order: 2
  }
]

and then call it with the current instance

renderComponent() {
    const step = constants.COMPLIANCE_CREATE_STEPS
       .find(step => step.order === this.state.currentStep)

    const { component: Cmp, props } = step

    return <Cmp {...(typeof props === 'function' ? props(this) : props)} />
}
Yury Tarabanko
  • 39,619
  • 8
  • 73
  • 90
0

You are not declaring handleChange method inside your component's class, and typing

<BasicInfo handleChange={this.handleChange} />

you are saying that it can be found inside component, which is not true.