Extelliqent
Extelliqent

Reputation: 1858

React Creating Menu items by a function

I have a menu with list items like below

   <MenuItem
      //className={this.classes.menuItem}
      onClick={this.handleClose}
    >
      <NavLink
        to={Constants.pagesURL+page}
        //className={this.classes.menuItemAnchor}
      >
        {Constants.pagesName+page}
      </NavLink>
    </MenuItem>

I want to wrap this with menuItem(page) function so within the page, all I need to do is {this.menuItem('Home')} and {this.menuItem('Page1')} to get menu items populated, easy and clean..

The struggle is I want the name I send when calling the function to be added to the Constant name.. For example, if I do {this.menuItem('Home')} then {Constants.pagesName+page} needs to be actually {Constants.pagesNameHome}..

I tried as above with adding + in front of page I send in, not working.. I tried {Constants.pagesName[page]} not working, I tried to create let pageName = 'pagesName'+page; then doing {Constants.pagesName} that didn't work either. How can I get this work?

As it is {Constants.pagesURL+page} I get 'undefinedHome' and 'undefinedPage1'...

Upvotes: 0

Views: 513

Answers (2)

Extelliqent
Extelliqent

Reputation: 1858

Okay this was rather easy as I expected.. Playing around, I figured this is the way to go..

{Constants['pagesURL'+page]}

Works as a charm!

Full code:

   menuItem(page) {
      return(
        <MenuItem
          //className={this.classes.menuItem}
          onClick={this.handleClose}
        >
          <NavLink
            to={Constants['pagesURL'+page]}
            //className={this.classes.menuItemAnchor}
          >
            {Constants['pagesName'+page]}
          </NavLink>
        </MenuItem>
      )
    }

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53874

Did you try:

const menuItem = (page) => `${Constants.pagesURL}${page}`;

Upvotes: 1

Related Questions