Jieunny์˜ ๋ธ”๋กœ๊ทธ

S3) Unit 1. [์‹ค์Šต] Tree UI ๋ณธ๋ฌธ

CodeStates/Training

S3) Unit 1. [์‹ค์Šต] Tree UI

Jieunny 2023. 2. 14. 16:00

๐Ÿ“ฃ ์žฌ๊ท€๋กœ Tree UI ๊ตฌํ˜„ํ•˜๊ธฐ

1๏ธโƒฃ Test ์กฐ๊ฑด

โœ”๏ธ <ul id="root"> ์•ˆ์— tree view๋ฅผ ๊ตฌ์„ฑํ•ฉ๋‹ˆ๋‹ค.
โœ“ ul#root ์—˜๋ฆฌ๋จผํŠธ๊ฐ€ ์กด์žฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
โœ“ ul#root ์—˜๋ฆฌ๋จผํŠธ ์•ˆ์— tree view๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

โœ”๏ธ menu ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด tree view๋ฅผ ๊ตฌ์„ฑํ•ฉ๋‹ˆ๋‹ค.
โœ“ ul#root ์—˜๋ฆฌ๋จผํŠธ ์•ˆ์— ์นดํ…Œ๊ณ ๋ฆฌ(์Œ๋ฃŒ, ์Œ์‹, ๊ตฟ์ฆˆ, ์นด๋“œ)๋ฅผ ๋ Œ๋”๋งํ•  4๊ฐœ์˜ li ์—˜๋ฆฌ๋จผํŠธ๊ฐ€ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
โœ“ ์นดํ…Œ๊ณ ๋ฆฌ(์Œ๋ฃŒ, ์Œ์‹, ๊ตฟ์ฆˆ, ์นด๋“œ) ์—˜๋ฆฌ๋จผํŠธ ์•ˆ์—๋Š” ๊ฐ๊ฐ ์ž์‹ ๋…ธ๋“œ๋ฅผ ๋ณด์—ฌ์ฃผ๊ณ  ๊ฐ์ถฐ์ค„ checkbox๊ฐ€ ์กด์žฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
โœ“ ์Œ๋ฃŒ, ์Œ์‹, ๊ตฟ์ฆˆ, ์นด๋“œ ์นดํ…Œ๊ณ ๋ฆฌ ์ด๋ฆ„(name)์„ span ํƒœ๊ทธ๋กœ ๊ฐ์‹ธ์•ผ ํ•ฉ๋‹ˆ๋‹ค.
โœ“ ์ž์‹ ๋…ธ๋“œ๊ฐ€ ์—†๋Š” ๋ฐ์ดํ„ฐ์˜ ๊ฒฝ์šฐ, li ์—˜๋ฆฌ๋จผํŠธ ์•ˆ์— ๋‹จ์ˆœํžˆ ์ด๋ฆ„(name)๋งŒ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค. (checkbox ๋ฐ span, ul์„ ํฌํ•จํ•˜๋ฉด ์•ˆ๋ฉ๋‹ˆ๋‹ค)
โœ“ ์ž์‹ ๋…ธ๋“œ๊ฐ€ ์žˆ๋Š” ๋ฐ์ดํ„ฐ์˜ ๊ฒฝ์šฐ, li ์—˜๋ฆฌ๋จผํŠธ ์•„๋ž˜์— ์ž์‹ ๋…ธ๋“œ๋ฅผ ๋ Œ๋”๋งํ•  ์ƒˆ๋กœ์šด ul์ด ์กด์žฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. (1)
โœ“ ์ž์‹ ๋…ธ๋“œ๊ฐ€ ์žˆ๋Š” ๋ฐ์ดํ„ฐ์˜ ๊ฒฝ์šฐ, li ์—˜๋ฆฌ๋จผํŠธ ์•„๋ž˜์— ์ž์‹ ๋…ธ๋“œ๋ฅผ ๋ Œ๋”๋งํ•  ์ƒˆ๋กœ์šด ul์ด ์กด์žฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. (2)
โœ“ type ์†์„ฑ์ด item์ธ ๊ฐ์ฒด๋Š” li ํƒœ๊ทธ๋กœ name ์†์„ฑ๊ฐ’์„ ๊ฐ์‹ธ์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

2๏ธโƒฃ ์ž‘์„ฑ ์ฝ”๋“œ

const root = document.getElementById('root');
function createTreeView(menu, currentNode) {
  // TODO: createTreeView ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”.

  // root ์—˜๋ฆฌ๋จผํŠธ์•ˆ์— ์นดํ…Œ๊ณ ๋ฆฌ li ๋งŒ๋“ค๊ธฐ
  for(let i=0; i<menu.length; i++){
    let category = document.createElement('li');
    if(menu[i].children){
    // children์ด ์žˆ์„ ๊ฒฝ์šฐ์—๋งŒ
      let chkBox = document.createElement('input');
      // ์ฒดํฌ๋ฐ•์Šค ๋งŒ๋“ค๊ธฐ
      chkBox.setAttribute('type', 'checkbox');

      let name = document.createElement('span');
      // name ๋งŒ๋“ค๊ธฐ
      name.textContent = menu[i].name;

      root.appendChild(category);
      category.appendChild(chkBox);
      category.appendChild(name);
      // ๊ฐ ์š”์†Œ root์— ์ž์‹์œผ๋กœ ์ถ”๊ฐ€ํ•ด์ฃผ๊ธฐ

      let innerUl = document.createElement('ul');
      // ul ์•ˆ์— ๋“ค์–ด๊ฐˆ ul ๋งŒ๋“ค๊ธฐ(์žฌ๊ท€ ํ•จ์ˆ˜์— ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ค„ ๊ฐ’)
      category.appendChild(innerUl);

      currentNode.appendChild(category);
      // ํ˜„์žฌ ๋…ธ๋“œ์— ํ˜„์žฌ ์ž‘์—…ํ•˜๊ณ  ์žˆ๋Š” ๋…ธ๋“œ ์ถ”๊ฐ€
      // ์žฌ๊ท€๋กœ ํ˜ธ์ถœ๋  ์ˆ˜๋ก ๋Š˜์–ด๋‚œ๋‹ค.

      createTreeView(menu[i].children, innerUl);
      // ๋ฐ‘์— ์ž์‹์ด ์žˆ์œผ๋ฉด ์žฌ๊ท€๋กœ ํ•จ์ˆ˜ ๋ถˆ๋Ÿฌ์„œ ๊ทธ ์ž์‹๋“ค๋„ ๋˜‘๊ฐ™์ด ๋ Œ๋”๋ง ํ•ด์ฃผ๊ธฐ
    }
    else{     
    // ์ž์‹์ด ์—†๋Š” ๊ฒฝ์šฐ
      root.appendChild(category);
      category.textContent = menu[i].name;
      currentNode.appendChild(category);
    }

  }
}

createTreeView(menu, root);

3๏ธโƒฃ ์‹œ์—ฐ ํ™”๋ฉด