Conditional rendering or toggling `hidden` classes?

(Yang Shun Tay) #1

At my company, we use React for building our management interface, which consists of many CRUD forms. There are many form elements on that page and only users with certain roles/permissions will get to see certain form inputs. This brings the question of whether to use conditional rendering such as ? <input type="text" /> : null

or conditionally setting the hidden class:

<input type="text" className={classnames({ hidden: ! })} />

What are the guidelines as to when to use which?

(Sophie Alpert) #2

In most cases it’s better to not render the field at all, so that React doesn’t need to consider it and no DOM nodes are created. (If you’re frequently toggling between a field being shown or not, hiding it temporarily can be a better option so that it doesn’t need to be recreated constantly, but that doesn’t sound like your case here.)

(Janaka Stevens) #3

Assuming hidden is equivalent to display: ‘none’ then on a complex page I experienced a noticeable performance hit using display: ‘none’. So on those components that are sometimes hidden I generally have the first line of render if (this.props.hide) return null;. Performance is great then.

(João Vitor) #4

I have the following scenario:

let render = ()=>{
            return <Message value={"Pick a repository!"} />
            return <Loading />
        else if(props.error)
            return <Message value={"An error occurred!"} />
            if( !== 0)
                return <RepositoryList repos={} />
                return <Message value={"No repositories found!"} />

This function is constantly called, and the Loading component has a lot of CSS and HTML and I think that recreating it several times isn’t good. Should I use classes to toggle Loading?

(Natalia Vidal) #5

Could it make sense or is there a way to have a mixture? Lets say the content that might show or not on the page could be a more complex piece of HTML, there might not be a point in the initial render since they might not open it, but once they’ve opened it they might close it an open it again, in which case conditional rendering would keep mounting and unmounting the element…
So I was wondering if it could make sense to have separate ways of controlling the initial visualization of the element with conditional rendering and then a way to hide it/show it and how could that be done.

(Eitan) #6

The “react” JSX way to do this looks like that:

  <div>Show always</div>
  { props.showMsg && ( <div>Show conditional</div> ) }