How to show/hide ReactJS components

user3317868 picture user3317868 · Feb 27, 2014 · Viewed 16.6k times · Source

Trying to learn ReactJS.. but what confuses me is the rendering of the component. Every example I've seen defines a React component class and at the end has something like:

React.renderComponent(
  <comp attr="value"" />,
  document.getElementById('comp')
);

I understand that it replaces the 'comp' element with my component.. that's great. But it seems if I load 20 components, all 20 render. However, I only want to render some and not all, but use all throughout my SPA. I am using DirectorJS router, and depending on if a user logs in or not, and/or goes to certain links, I want to only show one or so of components. I can't seem to find any info/examples/tutorials on how to dynamically manage showing or hiding react components. More so, what i'd really like to do is load partials depending on links clicked and in those partials they would use react components, so only at that time load/use the component. Is this possible..if so how might I handle this? I could live with loading 20+ components one time the first time the app is loaded, but i'd prefer to only load them if the partial a component is displayed on is loaded.

Answer

chenglou picture chenglou · Feb 27, 2014

First, render only what's necessary. It's easier to track and it's faster.

To actually "swap between pages", it's as simple as, well, setting a variable in your state/props, and use that var to conditionally render whatever you need. The role of selectively rendering whatever you want naturally goes to the parent component. Here's a working fiddle with Director: http://jsfiddle.net/L7mua/3/

Key part, in App:

render: function() {
  var partial;
  if (this.state.currentPage === 'home') {
    partial = <Home />;
  } else if (this.state.currentPage === 'bio') {
    partial = <Bio />;
  } else {
    // dunno, your default page
    // if you don't assign anything to partial here, you'll render nothing
    // (undefined). In another situation you'd use the same concept to
    // toggle between show/hide, aka render something/undefined (or null)
  }
  return (
    <div>
      <div>I am a menu that stays here</div>
      <a href="#/home">Home</a> <a href="#/bio">Bio</a>
      {partial}
    </div>
  );
}

Notice that beyond the HTML-looking JSX syntax, you're really just using JavaScript. Conditionals still work, iterations still work, etc.