Site-specific components in a (React) multi-site
Published on in Clean code, JavaScript and React
Last updated on
A multi-site React project has likely two kinds of components: common components and site-specific components. There are a few ways to handle site-specific logic in common components.
- Common components are used by two or more sites
and reside e.g. under the
src/common/
folder. - Site-specific components are used only by one site
and reside e.g. under the folders
src/site-a/
,src/site-b/
and so on.
An example of a common component is Link
:
a hyperlink with certain styles and logic,
used on all sites for most links.
Let's say that Site A,
and only that site,
requires some extra logic in the Link
component.
What are my options?
Let's think:
- Add the extra logic to the common
Link
component. This would be messy, because the common component would then have site-specific logic in it. - Create an entirely separate, site-specific
Link
component for Site A. I don't like this option because the common and site-specificLink
components would have lots of duplicate code. Links are very common, so any future changes would have to be made to two components. - Create a "child component" for Site A,
so that the site-specific component
ultimately renders the common
Link
component. This would be nice, but the problem would be that developers would need to remember to import the site-specific component when working on Site A's code, and to import the common component when working on the other sites' codes.
I eventually found a way to avoid the problem in the third option! Behold: Using ESLint to restrict where files can be imported from.