React.createClass vs extend Component

I’m getting mixed messages about which method to use to create a react component. The To-Do tutorial used the extended method. The tutorial at React.js, and nearly every other code example I’ve found, uses React.createClass. I managed to muddle through the official React tutorial, transcribing everything to the ‘new’ way, but there are some core concepts that are not explained very well / not working very well.

For example, I’m having a problem with state. I used the constructor trick to establish state in my component. . But when I handle a click event, and update the state variable with setState, printing this.state.myvar to the console at various points in my code actually returns different results. This is highly confusing.

Also, I’m trying to render subcomponents of a complex dynamic form based on selections from the initial part of the form. In Blaze, this was trivial using session variables like this:

`{{#if period_is_year}}
    {{> monthofyear_selector}}
    {{> dayofmonth_selector}}
   {{/if}}

   {{#if period_is_month}}
      {{> dayofmonth_selector}}
   {{/if}}

   {{#if period_is_week}}
    {{> dayofweek_selector}}
   {{/if}}`

But for the life of me I can’t figure out how to conditionally - and dynamically - show or hide nested react components. This is so frustrating. There are methods in the createClass examples that don’t seem to exist related to mounting and unmounting components, and I can’t find their analog using the extend Component way. Any help is appreciated. Thanks.

-Jerimiah

This is my go to reference: https://toddmotto.com/react-create-class-versus-component/

As for the conditionals, I think you want to do this:

render(){ return(
  <div>
    { this.state.period_is_month ? 
      <DayOfMonthSelector />
      : null
    }
  </div>
)}
2 Likes

Thanks, that gives me something fresh to chew on. I have actually been poring over that same if-else link you posted, but didn’t glean the function above. Thanks for putting it in a new context.

Another thing that I’m totally confused about is what to do with all the ReactDOM.render calls I see in all the docs. It must be the analog to the render(){ return( ) used in the ‘extend Component’ method, since the original code snippet from that page looks like this:

ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);

I’ll check out the toddmoto.com link and see if I can wrap my head around this. Thanks again.

WOW. That link you posted was exactly what I needed. That content should be linked to in the introduction to the tutorial on the Meteor site! It is essential. Here it is once again:

Thanks once again.

-Jerimiah

2 Likes

Jupp, that link would have helped me a lot when I started with meteor+react a few weeks ago.
+1 for refering to it in the guide