Search code examples
reactjsrefactoring

Refactoring React application


Could you share your point of view about the best approach to change element`s style dynamicaly. I am refactoring data table with virtual scroll component, where I need to change the first and last lines' height dynamicaly. Now I change it by specifying element's inline styles like that:

<tr style={{ height: `${scroll.firstRowHeight}px` }}></tr>

Is that OK or it is better to select element with useRef or document.querySelector first and then change the height?

I am asking this question because I've come accross different opinions:

  • some people say that React team even encourages using inline styles (I tried to find this fact, but didn't manage to).
  • some people say that it is bad approach, because it is difficult to find the place where inline style has been applied and there may be issues with redefining the style.

Solution

    1. useRef and document selectors are adding changes to the real DOM and not the virtual DOM. Changes to virtual DOM is preferred since react knows about it and applies changes to the real DOM accordingly (See reconciliation in React)
    2. Inline styles is alright. If you're able to scale and organise it accordingly then good for you. In React Native for example, we use stylesheet which is almost like inline styles in React, hence it's a tried and tested approach. But for the web we have more options, styled components, tailwind, SCSS, CSS modules etc. Inline styles are one of the many options available. So it collectively depends on the maintainers and the developers of the project to decide on what to choose.