skip to Main Content

I am using reactJS and I would like to hide a div on smaller screen (width<768px). I have two options here:

First Method:

{
 !!isSmallerScreen ? 
 <div className="icon">Icon</div>
 : <div className="name">Name</div>
}

Description: isSmallScreen is a boolean variable. This way will not even show other div in source code.

Second Method:

   <div className="icon hidden-md-up">Icon</div>
   <div className="name hidden-sm-down">Name</div>

Description: I’m using twiitter bootstrap here which will add display: none on other div.

P.s. I know bootstrap is also using javascript but my question is which approach is better to use? Infact I am confused whether to use bootstrap or not as I’m already using css3 flexbox system with postcss and cssnext.

Your suggestions will be highly appreciated. Thanks for your time in advance.

3

Answers


  1. In the second method, though will hide the div but still remain in the DOM.

    You should use ReactJS method and not render the div is possible.
    The reason being if you don’t need a dont unnecessarily create it and make the DOM heavy.

    Hope this helps.

    Login or Signup to reply.
  2. Matter of preference (and minimal perfomance issue probably not worth stalling the decision making).

    Personally I would go with the second method for the simple reasons that:

    1. Easier to add transitions (fade in/out)
    2. A little cleaner
    3. Your vdom will stay the same – if a 3rd party, or yourself,
      later decide to manipulate the dom outside react, you know
      it will be consistent. (ie, selecting nth-child, etc). no surprises.

    But, ultimately up to you 🙂

    Login or Signup to reply.
  3. As dattebayo pointed out, it is bad practice to add unnecessary elements to the DOM. When making a decision in how something should be hidden, ask yourself a couple questions;

    Will this element alternate state? Not this.state but whether or not it is hidden.

    If not, then conditional rendering is the clear choice.

    render() {    
       return (
           this.props.isSmallScreen ?
               <SmallScreenElement /> :
               <BigScreenElement />;
       );
    }
    

    If yes, will it alternate state frequently?

    If yes, CSS is likely the choice for this particular element.

    Otherwise stick with conditional rendering.

    I hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search