I am building a menu in React by having an empty array of menuData and then pushing data to that based on which user is logged into the site and which environment they are using. The menu is built using functions that build specific parts of the menu. As I continue to add menu items this file is becoming massive and ugly. I would like to extract the menu building functions to a util class that will build the menu based on the current logged in user and environment. This is what a generic menu item looks like:
getMenuDataForUser4() {
this.state.menuData.push({
menuName: 'About Me',
iconURL: 'pictureOfTrash.jpg',
children: [
{
menuName: 'Bio ',
children: []
route: '/bio',
}
]
});
Currently, I have a super ugly if statement that checks the current user and environment and then calls the corresponding building function. It looks like:
getMenuDataForUser() {
if (this.state.user.includes('user1')) {
this.getStandardMenuData();
this.getMenuDataForUser2();
this.getMenuDataForUser4();
if (this.state.isSpecificEnvironment === true) {
this.getMenuDataForThatEnvironment();
}
} else if (this.state.user.includes('user2')) {
this.getMenuDataForUser2();
if (this.state.isSpecificEnvironment === true) {
this.getMenuDataForThatEnvironment();
}
} else if (this.state.user.includes('user3')) {
this.getStandardMenuData();
if (this.state.isSpecificEnvironment === true) {
this.getMenuDataForThatEnvironment();
}
} else {
this.getMenuDataForUser4();
}
I'm sure there is a cleaner way to get the same result, perhaps using a switch statement or something but I haven't been able to come up with a clean way to refactor. My main goal is to move these functions to a util class called like MenuBuilder and then somehow call those functions in the parent class. I know you can pass functions to children by using
<MenuBuilder getMenuDataForSpecificUser={this.getMenuDataForSpecifcUser.bind(this)}
But how can I call it from the parent class? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire