skip to Main Content

I cant seem to render the dropdown items.Not sure I have the syntax right, but the log shows

{menu: Array(5)}
menu: (5) ['Guitar', 'Ams Work', 'Learning', 'Food', 'Exercise']

Heres the relevent code.

const data = ["Guitar", "Ams Work","Learning","Food","Exercise"]
function App() {

  return (
    <div className="container">
      <Header />
    <ToggleVisibility basicexample={<MyDropdown menu = {data}/>} /> 
      <Footer />
    </div>
  );
}

….

function MyDropdown(menu) {
  console.log(menu)
  return (
    
    <Dropdown>
      <Dropdown.Toggle variant="success" id="dropdown-basic">
        Dropdown Button
      </Dropdown.Toggle>

      <Dropdown.Menu >
        <Dropdown.Item href="#/action-1">{menu[0]}</Dropdown.Item>
        <Dropdown.Item href="#/action-2">{menu[1]}</Dropdown.Item>
        <Dropdown.Item href="#/action-3">{menu[2]}</Dropdown.Item>
      </Dropdown.Menu>
    </Dropdown>
  );
}

2

Answers


  1. The only argument given to a function component is the props, which is an object. You could destructure it to access the menu prop.

    Then, use Array#map to render a Dropdown.Item for each element of the array.

    function MyDropdown({ menu }) {
      return (
        <Dropdown>
          <Dropdown.Toggle variant="success" id="dropdown-basic">
            Dropdown Button
          </Dropdown.Toggle>
    
          <Dropdown.Menu>
            {menu.map((m, i) => <Dropdown.Item href={"#/action-" + i}>{m}</Dropdown.Item>)}
          </Dropdown.Menu>
        </Dropdown>
      );
    }
    
    Login or Signup to reply.
  2. Change menu

    function MyDropdown(menu) {
      return …
    }
    

    To props

    function MyDropdown(props) {
      return …
    }
    

    The menu is accessible via props.menu

    function MyDropdown(props) {
      return (
        <Dropdown>
          <Dropdown.Toggle variant="success" id="dropdown-basic">
            Dropdown Button
          </Dropdown.Toggle>
          <Dropdown.Menu>
            {props.menu.map((item, key) =>
              <Dropdown.Item
                key={key}
                href={`#/action-${key}`}
                children={item}
              />
            )}
          </Dropdown.Menu>
        </Dropdown>
      );
    }
    

    TypeScript –

    function MyDropdown(props: {
      menu: Array<string>
    }) {
      return …
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search