Skip to content

Instantly share code, notes, and snippets.

@BunHouth
Last active May 16, 2020 10:54
Show Gist options
  • Save BunHouth/682f3a5d76b8aa27e63dc3e4994ad994 to your computer and use it in GitHub Desktop.
Save BunHouth/682f3a5d76b8aa27e63dc3e4994ad994 to your computer and use it in GitHub Desktop.
import React, {useState} from "react";
import "./App.css";
const data = [
{id: 1, name: "meat", parent_id: null},
{id: 2, name: "vegi", parent_id: null},
{id: 3, name: "drink", parent_id: null},
{id: 4, name: "fish", parent_id: 1},
{id: 5, name: "beef", parent_id: 1},
{id: 6, name: "pork", parent_id: 1},
{id: 7, name: "raw", parent_id: 2},
{id: 8, name: "boiled", parent_id: 2},
{id: 9, name: "carbonate", parent_id: 3},
{id: 10, name: "fried rice beef", parent_id: 5},
{id: 11, name: "fried rice pork", parent_id: 5},
{id: 12, name: "morning glory", parent_id: 8},
{id: 13, name: "coca", parent_id: 9},
{id: 14, name: "fried rice beef parent 10", parent_id: 10},
{id: 16, name: "fried rice beef parent 10-1", parent_id: 10},
{id: 15, name: "fried rice pork parent 14", parent_id: 14}
];
const findChilds = id => {
const results = [];
data.map(child => {
if (child.parent_id === id) {
results.push(child);
child.childs = findChilds(child.id);
}
});
return results;
};
const records = data
.filter(object => !object.parent_id)
.map(object => {
object.childs = findChilds(object.id);
return object;
});
const keyBy = (array, key) =>
(array || []).reduce((r, x) => ({...r, [key ? x[key] : x]: x}), {});
function App() {
const [data, setData] = useState([records]);
const onChange = e => {
const value = e.target.value;
const level = Number(e.target.dataset.level);
const newData = data.slice(0, level + 1);
const activeData = newData[level];
const key = keyBy(activeData, "id");
const record = key[value];
if (record && (record.childs || []).length) {
newData.push(record.childs);
}
setData([...newData]);
};
const findChild = (items, id) => {
return (
items.filter(item => {
if (item.id === id) {
return true;
} else {
return findChild(item.childs || [], id);
}
}).length > 0
);
};
const findParentByChildId = id => {
const results = records.filter(item => {
return findChild(item.childs || [], id);
});
return results.length ? results[0].id : null;
};
const parentId = findParentByChildId(7);
const renderElement = () => {
return data.map((item, index) => {
return (
<select onChange={onChange} key={index} data-level={index}>
<option>Select Options</option>
{item.map(option => {
return (
<option key={option.id} data-level={index} value={option.id}>
{option.name}
</option>
);
})}
</select>
);
});
};
return <div className="App">{renderElement()}</div>;
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment