How to set prop in react bootstrap(Dropdown) from parent

Viewed 966

I am customizing the Dropdown from the react-bootstrap react to create the component, but I have trouble retrieving the props. This is my code in index.js, src/components/Dropdown/index

import React from 'react';
import {Dropdown} from 'react-bootstrap';
import '../Dropdown/index.css'

const DropdownItem = (name) => {
  return(
    <Dropdown>
      <Dropdown.Toggle className="dropdown-button">
        Selection
      </Dropdown.Toggle>

      <Dropdown.Menu className="dropdown-menu">
        <Dropdown.Item href="#/action-1">{name}</Dropdown.Item>
        <Dropdown.Item href="#/action-2">{name}</Dropdown.Item>
      </Dropdown.Menu>
  </Dropdown>
  );
}

export default DropdownItem;

The name I will render from app.js(src/app) is passed into the dropdown item like this

< DropdownItem name="Milk Tea"/> 

But If I have a lot of items, how can I print them all in one dropdown group? enter image description here

I can not do like this

< DropdownItem name="Milk Tea"/> 
< DropdownItem name="Fruit"/>

It's will render many dropdowns not drop item

Your help is very useful

1 Answers

You got the child component logic wrong. Your Child component is the whole Dropdown component as per I can see your code. Therefore, you will have to pass down array of names as props.

Example.

import React from "react";
import { Dropdown } from "react-bootstrap";
import "../Dropdown/index.css";

const DropdownItems = ({ nameList }) => {
  return (
    <Dropdown>
      <Dropdown.Toggle className="dropdown-button">Selection</Dropdown.Toggle>

      <Dropdown.Menu className="dropdown-menu">
        {nameList.map((name, index) => (
          <Dropdown.Item href={`#/action-${index}`}>{name}</Dropdown.Item>
        ))}
      </Dropdown.Menu>
    </Dropdown>
  );
};

In App.js

<DropdownItems nameList={["Milk Tea","Fruit"]} />
Related