i got a project has 3 users roles (parent - child - teacher) and each role has 2 different statues (booked - unbooked) that changes the UI and logic.
Example:- the home header in the home page will be change based on the user role and the statues.
How to solve this problem without big chain of conditions ?
Wrong Answer ❌
switch (userRole) {
case 'parent':
switch (status) {
case 'booked':
return // BookedParentComponent
case 'unbooked':
return // UnBookedParentComponent
}
case 'child':
switch (status) {
case 'booked':
return // BookedChildComponent
case 'unbooked':
return // UnBookedChildComponent
}
case 'teacher':
switch (status) {
case 'booked':
return // BookedTeacherComponent
case 'unbooked':
return // UnBookedTeacherComponent
}
}
With Dynamic components, no conditionals required.
The following sample code demoes it.
Note : For brevity, sample code handles only two components.
./src/App.js
export default function App() {
return (
<>
<DynamicComponent userRole="parent" status="booked" />
<br />
<DynamicComponent userRole="parent" status="unbooked" />
</>
);
}
function DynamicComponent({ userRole, status }) {
const Component = require(`./components/${status}${userRole}`).default;
return <Component />;
}
./src/components/bookedparent.js
export default function BookedParentComponent() {
return 'I am BookedParentComponent';
}
./src/components/unbookedparent.js
export default function UnBookedParentComponent() {
return 'I am UnBookedParentComponent';
}
Test run output
On load of the app
Citation: The Importance of React Dynamic Component Name: Insights