I often run into a bit more complex Reactjs components to build. Some that change part of their UI, or complete UI, based on some state change. Like login screen that displays "forgot password?" on login errors (only part of login popup UI) or transfer from register screen to "verify password" screen to "registration success/false" screen, which basically change complete popup UI (although really small UI).
What pattern you use for designing those components?
Options I'm thinking about are:
1) define constants in `render()` and then use some basic logic in return part of it
2) @calculated (MobX) method of the component class, or similar component class that returns JSX to be used in `render()`
3) separate each little part into separate component, preferably stateless functional component and then import/require it
I think that it depends on the scenario. For different screens or popups, separate components definitely make sense because you don't want a single component to be handling too many responsibilities (or at least not inlined, obviously you can import into a main LoginPage component). However, if you simply have some conditional logic to render a link or button, that can either go inline of the render() method, or I would suggest put it into its own class method (I usually use the convention of prefixing it with render, like renderForgotLink(). I prefer this convention of class methods instead of constants in render() because when I look at the render()method, I want to know exactly what will be shown without having to scroll down too far.
Lorefnon
Open Web Enthusiast
Separate components are usually ideal from maintenance perspective. This aligns with the recommendation from the MobX team as well.
I have found that having too many files with tiny components often becomes unwieldy so I usually group components into modules and have many components in a file. Non-reusable components are explicitly marked as
@privateeven if they are exported for unit-testing.I try to prefer stateless components, but in practice many of my components end up being classes either because I need dependency injection through Inversify injected properties, or because I need custom optimisations in
shouldComponentUpdate.It would be ideal if you can use Immutable through and through and be able to just rely on shallow comparisions. I can not currently afford to do so due to myriad integrations with legacy ui components, charting libraries etc.