DEV Community 👩‍💻👨‍💻

Discussion on: Build a "Pluggable" Widget for your Web App

Collapse
 
lexswed profile image
Lex Swed • Edited on

Maybe I didn't understand some parts, but few comments on React usage:

  • please, don't use renderThing, here's the example of the discussion around this antipattern: renderThing. Even if App is rendered once (and hence all your renderX functions are created once as if they were defined outside render method as separate components), it's harder to reason about its internals.
  • your config manipulations are very confusing. As I understand, all you want is to rerender your app on config change
window.addEventListener('message', (event) => {
 event.preventDefault();
 if (!event.data || (typeof event.data !== 'string')) return;
 const config: IConfig = JSON.parse(event.data);
 return render(
   <App config={config} />, // why to stringify? why to use Context?
   document.body
 );
});

ReactDOM will automatically pick up the changes instead of rendering whole new thing in both cases.

So then it's very easy to work with the component:

const App: React.FC<{ config: IConfig }> = ({ config }) => {
  const [page, setPage] = useState<Number>(1);

  const handlePageChange = page => setPage(page)

  return (<div className="h-100 w-100 border rounded">
    <Header />
    <Links onPageChange={handlePageChange}/>
    <ActiveComponent config={config} onPageChange={handlePageChange} />
  </div>);
 }
Collapse
 
soorajsnblaze333 profile image
Sooraj (PS) Author

Thanks for pointing out these points Lex, appreciate you for the resources :).
But in your second point, I actually didn't aim to rerender the component on config change, I wanted to "render" the main component only if the config existed and render nothing if there was no config passed to the react app. Something like an init method. This config was from the recieved at the message event and then I rendered the component only once :)