Home > OS >  How can I create a menu with my json info with REACT
How can I create a menu with my json info with REACT

Time:05-16

what I try to do is to have the same display as this picture : enter image description here

So in my menu the plant type (Type of plant1) is displayed above a gray bar and when you click on the down chevron then you can see all the plants name, related to this type, with checkboxes on left, by default there will be all checked. And the blue rectangle indicates the number of plants that have been selected. How can I do that, which package can help me in REACT?

Here my plants.json :

{
    "plants_type": [
        {
            "_id_type": "1",
            "name_type": "Type of plant1",
            "plants": [
                {
                    "name": "Plant1.1",
                    "_id": "2"
                },
                {
                    "name": "Plant1.2",
                    "_id": "3"
                }
            ]
        },
        {
            "_id_type": "4",
            "name_type": "Type of plant2",
            "plants": [
                {
                    "name": "Plant2.1",
                    "_id": "5"
                },
                {
                    "name": "Plant2.2",
                    "_id": "6"
                }
            ]
        }
    ]
}

CodePudding user response:

You can create a dropdown list on your own like below. I have added the logic of selecting items to the data itself.

You can keep a component called Category to keep a single state of the parent menu item. Whether it's open or not. Then iterate over the plants as checkbox inputs to make them selectable.

I have used a simple initialize function to make all the items selected initially. This should work as you expect. Add a console log of selectionMenu to see how selected property changes while toggling items.

Move the inline styles to CSS classes to make the code more clear.

const data = { plants_type: [ { _id_type: "1", name_type: "Type of plant1", plants: [ { name: "Plant1.1", _id: "2" }, { name: "Plant1.2", _id: "3" } ] }, { _id_type: "4", name_type: "Type of plant2", plants: [ { name: "Plant2.1", _id: "5" }, { name: "Plant2.2", _id: "6" } ] } ] };

const Category = ({ _id_type, name_type, plants, changeSelection }) => {
  const [toggleState, setToggleState] = React.useState(false);

  return (
    <div key={_id_type}>
      <div
        style={{
          cursor: "pointer",
          userSelect: "none",
          display: "flex",
          margin: "2px",
          backgroundColor: "lightgray"
        }}
        onClick={() => setToggleState((prev) => !prev)}
      >
        <div>{name_type}</div>
        <div
          style={{
            backgroundColor: "blue",
            color: "white",
            padding: "0px 10px",
            marginLeft: "auto"
          }}
        >
          {plants.filter(({ selected }) => selected).length}
        </div>
      </div>
      <div style={{ marginLeft: "10px" }}>
        {toggleState &&
          plants.map(({ name, _id, selected }) => (
            <div key={_id}>
              <input
                key={_id}
                type="checkbox"
                value={name}
                checked={selected}
                onChange={(e) => changeSelection(_id_type, _id, e.target.value)}
              />
              {name}
            </div>
          ))}
      </div>
    </div>
  );
};

const App = () => {
  const initializeSelectionMenu = (data) => {
    return data.map((item) => {
      return {
        ...item,
        plants: item.plants.map((plant) => ({ ...plant, selected: true }))
      };
    });
  };

  const [selectionMenu, setSelectionMenu] = React.useState(
    initializeSelectionMenu(data.plants_type)
  );
  
  console.log(selectionMenu);

  const changeSelection = (catId, itemId, value) => {
    setSelectionMenu((prevSelectionMenu) =>
      prevSelectionMenu.map((item) => {
        if (item._id_type === catId) {
          return {
            ...item,
            plants: item.plants.map((plant) => {
              if (plant._id === itemId) {
                return { ...plant, selected: !plant.selected };
              }
              return plant;
            })
          };
        }
        return item;
      })
    );
  };

  return (
    <div>
      {selectionMenu.map((item) => (
        <Category
          {...item}
          changeSelection={changeSelection}
          key={item._id_type}
        />
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

  • Related