2

Can anyone please help me understand what is going on here in some code I need to refactor.

I have a component which looks pretty ordinary such as this:

export default class MyContainer extends PureComponent {
  //props
  //state
  //render()
  //etc.
}

This is then passed in as props to another component like this:

export class ParentContainer
render() {
    return (
      <div>
        <Tabs
          home={MyContainer}
        />
      </div>
    );
  }
}

but what's got me confused is inside Tabs, it requires a function.

export default class Tabs extends PureComponent {
   static propTypes = {
    home: func.isRequired,
  }
}

This raises many questions for me:

What does this home={MyContainer} do? Just instantiate a component inline with all default props maybe? I haven't seen that syntax before. And why is this component acting as a function. Is there something going on behind the scenes like react is implicitly converting the component to the render() function perhaps?

If I try instantiate it in the 'normal' way so that I can add some new props i.e. {<MyContainer />} I get a runtime error saying that Tabs is expecting a function? Should I just change the Tabs to expect an object to get this working?

1 Answer 1

1

What does this home={MyContainer} do?

The component MyContainer is passed as a prop to Tabs component. Tabs will in turn decide when to render MyContainer component.

And why is this component acting as a function. Is there something going on behind the scenes like react is implicitly converting the component to the render() function perhaps?

React Components are ES6 classes. All classes in JavaScripts are functions by nature. The class syntax is just a syntactic sugar to define a function. That's why home: func.isRequired means, a component should be passed to home prop.

If I try instantiate it in the 'normal' way so that I can add some new props i.e. {< MyContainer />} I get a runtime error saying that Tabs is expecting a function? Should I just change the Tabs to expect an object to get this working?

No. When you pass {< MyContainer />} to home, you are trying to execute the component while setting it in home prop. You should only pass the reference to the home prop like this home={MyContainer}

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

2 Comments

So, is there any way now to pass in a reference to a callback function in the parent component ? I really need this child component to be able to alter the state of the parent e.g pseudo code {MyContainer onSwitch=this.onSwitch}
You can try home={() => < MyContainer propName={'value'} />}

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.