javascriptreactjsdom

Is it good practice to manipulate DOM in ReactJS?


Hi I am very new to ReactJS. I am building a Sidebar navigation for a website. The navigation has 3 levels so i built a recursive navigation bar with below logic:

for all items in the array
  if item has childern
    buildNavigation()
  else return;
}

Initially all children are hidden but on-click of a menu-item I "make it visible" by traversing the DOM.

enableDropdown(e) {
  e.stopPropagation();
  let dropdownContent = e.currentTarget.getElementsByClassName(
    'dropdown-container'
  )[0];
  let directionIcon = e.currentTarget.getElementsByClassName(
    'menu-direction'
  )[0];
  // Toggle dropdown & animate caret symbol
  if (dropdownContent.style.display === 'block') {
    directionIcon.classList.add('direction-icon-reset');
    directionIcon.classList.remove('direction-icon-active');
    dropdownContent.style.display = 'none';
  } else {
    directionIcon.classList.add('direction-icon-active');
    directionIcon.classList.remove('direction-icon-reset');
    dropdownContent.style.display = 'block';
  }
}

enableSubMenu(e, link) {
  e.stopPropagation();
  this.props.history.push(link);
  let lis = document.getElementsByClassName('no-child');
  for (let i = 0; i < lis.length; i++) {
    lis[i].classList.remove('active');
  }
  e.currentTarget.classList.add('active');
}

But received a huge backlash during code review for doing the DOM manipulation directly.

So Is it good practice to manipulate DOM in ReactJS?

What did I miss? What should I know before building ReactJS Apps?


Solution

  • In most cases, and I really mean most cases, you would not need to manipulate the DOM. So Yeah it's not good practice especially in this case where you can use JSX very easily to conditionally toggle those classes inside of your render method. Doing it this way is basically not using React for its main purpose which is keeping the DOM up to date with the state of your application. As far as what you need to know before you develop in React, basically if you read a little bit of the documentation you'll realize how easily you can utilize state and JSX to solve these problems more easily and in a way more maintainable and readable fashion.

    One reason I might add for this is handling the UI state of your application without React and manually manipulating DOM is very error prone and hard to maintain. It will get out of control quite fast and lead to hard to debug issues regarding a poorly maintained state.

    https://reactjs.org/docs/state-and-lifecycle.html