Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/hide ReactJS components

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.

like image 389
user3317868 Avatar asked Feb 27 '14 07:02

user3317868


People also ask

How do I show hidden components in React Native?

This is an Example to Hide Show Component in React Native. To do this we will use a conditional operator and state. When we change the state view will re-render itself and after checking the state we will return the view or null. In this example, we are hiding and showing the image on a click of a button.


1 Answers

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 {
    // I don't know, 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.

like image 139
chenglou Avatar answered Oct 11 '22 13:10

chenglou