How to render ReactJS component from outside of JS class it's defined in and/or with dynamic id element name?

StackOverflow https://stackoverflow.com/questions/22110886

Pregunta

If I defined a ReactJS class in say dialog.js:

var divStyle = {
  padding: '15px',
  paddingBottom: '12px'
};

var Dialog = React.createClass({
 render: function() {
    return (
      <div style={divStyle}>...</div>
    );
  }
});

In the above I define a class.. but in every example I see there is also the React.renderComponent(<Dialog/>,document.getElementById('someId'));

The problem I have with this is.. if I want to use this component on different pages with different IDs to render it at, or perhaps for several different IDs, I can't hard-code the id in the actual class it's at. I supposed I can pass in the ID in some manner??

But furthermore, I also want to be able to render the component in say a different JS class, one loaded AFTER the loading of this js class. I have an app.js class for my SPA app, that is loaded last. In it, when a user clicks a link, I may want to only render this component at that time. I do realize in the render method I can control in some way whether or not it's actually rendered.. but my thinking is also to not even bothering inserting it into the DOM unless an action occurs. Sort of like lazy insertion I guess?

I've tried in my app.js:

function () {
  React.renderComponent(<Dialog/>,...);
}

but obviously this doesn't work as this JS is not a JSX JS file. So I tried using React.renderComponent(Dialog,...); thinking the Dialog class is globally defined, so it would be available, but that too fails.

So how do I use the Dialog class in another function to render it?

¿Fue útil?

Solución

I think you're getting something conceptually wrong here:

but in every example I see there is also the React.renderComponent(<Dialog/>,document.getElementById('someId'));

The fact that the short examples are followed by a renderComponent call is for the trivial reason to show the demos. Once again, keep in mind that in React, <Dialog /> desugars to Dialog(). If you don't call it nothing happens.

So, simply don't call until you need it.

Also, I don't understand what you mean by:

but obviously this doesn't work as this JS is not a JSX JS file

Since you can just process that file through JSX?

If you're having trouble mentally mapping JSX to functions and vice-versa: try the live compiler here: http://facebook.github.io/react/jsx-compiler.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top