ManuelDeLeon / viewmodel-react

Create your React components with view models.
MIT License
24 stars 3 forks source link

propTypes validation and default export #42

Closed davidsavoie1 closed 6 years ago

davidsavoie1 commented 6 years ago

Hi @ManuelDeLeon! I'd like to learn more about how exports are handled by ViewModel please. When I create a VM component like so:

MyComponent({ ... });

MyComponent is actually an undefined symbol (no const MyComponent = ...). I can only guess that the viewmodel-react-plugin or viewmodel-react itself is parsing my code when MyComponent is used in another React component and transforms it to a regular class with a named export... Is that about right?

I tested adding

MyComponent.propTypes = { foo: PropTypes.string.isRequired }

export default MyComponent;

after the VM component definition and it works, but I don't understand what's going on behind the scenes, since my IDE complains that MyComponent is not defined.

Is there a way to create a VM component other than with an undefined symbol, such as const MyComponent = new ViewModel.createComponent({ ... })?

ManuelDeLeon commented 6 years ago

In summary, if you write:

    Test({ render() {
      <div />;
    } });

It is the same as writing:

import ViewModel from "viewmodel-react";
import React from "react";
export class Test extends React.Component {
  render() {
    return <div />;
  }
  constructor(props) {
    super(props);
    ViewModel.prepareComponent("Test", this, {});
  }
}

So you end up with a exported class called Test.

If you use another component within another, the VM babel plugin will check if you're already importing it from somewhere else. If you are, then it doesn't do anything. If you're not, then it adds an import to the beginning of the file: import { MyComponent } from "./MyComponent/MyComponent";

Does this answer your question?

davidsavoie1 commented 6 years ago

Absolutely! Great, that's exactly what I was hoping for... It clarifies things a lot!