I
I
Ilya2019-10-13 21:39:33
React
Ilya, 2019-10-13 21:39:33

What is the best way to organize a directory state with drop-down lists?

I have a test directory with themes. Themes are usually 20 or more. Clicking on a topic will open a list of subtopics.

<div
  className="Topic"
  data-subtopic-list="subtopicList1"
  onClick={handleTopicClick}
>
  {subtopicLists.subtopicList1 && (
    <div className="Topic-SubtopicList">
      ...
    </div>
  )}
</div>

How do you like my state organization?
const [subtopicLists, setSubtopicLists] = useState({
  subtopicList1: false,
  subtopicList2: false,
  subtopicList3: false,
  subtopicList4: false,
  subtopicList5: false,
  subtopicList6: false,
  subtopicList7: false,
  subtopicList8: false,
  subtopicList9: false,
  subtopicList10: false,
  subtopicList11: false,
  subtopicList12: false,
  subtopicList13: false,
  subtopicList14: false,
  subtopicList15: false,
  subtopicList16: false,
  subtopicList17: false,
  subtopicList18: false,
  subtopicList19: false,
  extraSubtopicList1: false,
  extraSubtopicList2: false,
  extraSubtopicList3: false
});

const handleTopicClick = e => {
  e.preventDefault();

  const { subtopicList } = e.currentTarget.dataset;

  setSubtopicLists({
    ...subtopicLists,
    ...{ [subTopicList]: !subtopicLists[subTopicList] }
  });
};

Would it be better if we split the state into separate variables?
Any other refactoring advice would be greatly appreciated.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-10-13
@sidorchik

1. Brutal hardcoding.

subtopicList1: false,
subtopicList2: false,

It's even hard to imagine what's in the missing parts of the code. JSX also seems to be output for each theme separately. It is better to do all the repeating parts in cycle
2. Instead of
data-subtopic-list="subtopicList1"
 onClick={handleTopicClick}

it's better to just write
and
const handleTopicClick = subtopicList => {
  setSubtopicLists({
    ...subtopicLists,
    ...{ [subTopicList]: !subtopicLists[subTopicList] }
  });
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question