Joe C
Joe C

Reputation: 1855

How to pass props and their methods dynamically to a component in React?

I have a Parent Component that loads child components dynamically:

Parent Component:

// ... lifecycle methods et al

   setOverviewRef(ref) {
    this.OverviewHeader = ref;
  }

  setBowSizeCompareRef(ref) {
    this.bowSizeCompare = ref;
  }

  setDualVideoRef(ref) {
    this.dualVideoRef = ref;
  }

render() {

    const showComponent = (componentName, {refToPass, refMethod}) => {
      if (typeof this.state[`${componentName}`] !== undefined && this.state[`${componentName}`] !== null) {
        const Component = this.state[`${componentName}`].default;
        console.log('{refToPass, refMethod}: ', {refToPass, refMethod});
        return (
          <Component {...{ refToPass: this[`${refMethod}`] }} />
        );
      } else {
        return null;
      }
    }

    return (
      <section>
        <OverviewHeader overviewRef={this.setOverviewRef} />
        { showComponent('BowSizeCompareComponent', {refToPass: 'bowSizeCompareRef', refMethod: 'setBowSizeCompareRef' }) }
        { showComponent('DualVideoComponent', {refToPass: 'dualVideoRef', refMethod: 'setDualVideoRef' }) }
      </section>
    );
  }

Assuming that I want the BowSizeCompareComponent, how do I get it so the Component that is returned from showComponent is in the form:

<Component bowSizeCompareRef={this.setBowSizeCompareRef} />

If it was DualVideoComponent, should be in form:

<Component dualVideoRef={this.setDualVideoRef} />

Upvotes: 0

Views: 37

Answers (1)

Joe C
Joe C

Reputation: 1855

I needed to fix the structure of the passed in refObj to showComponent():

render() {

    const showComponent = (componentName, refObj) => {
      if (typeof this.state[componentName] !== undefined && this.state[componentName] !== null) {
    const Component = this.state[componentName].default;
    return (
      <Component {...refObj} />
    );
  } else {
    return null;
  }
};

    return (
      <section>
        <OverviewHeader overviewRef={this.setOverviewRef} />
        { showComponent('BowSizeCompareComponent', {bowSizeCompareRef: this.setBowSizeCompareRef }) }
        { showComponent('DualVideoComponent', {dualVideoRef: this.setDualVideoRef }) }
      </section>
    );
  }

Upvotes: 1

Related Questions