My goal is to add components dynamically on a page/parent component.
I started with some basic example template like this:
main.js:
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);
ReactDOM.render(<SampleComponent name="SomeName"/>, document.getElementById('myId'));
App.js:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
<div id="myId">myId div</div>
</div>
);
}
});
SampleComponent.js:
var SampleComponent = React.createClass({
render: function() {
return (
<div>
<h1>Sample Component! </h1>
</div>
);
}
});
Here SampleComponent is mounted to <div id="myId"></div>
node, which is prewritten in App.js template. But what if I need to add indefinite number of components to App component? Obviously I cannot have all the required divs sitting there.
After reading some tutorials I still have no understanding of how components are created and added to parent component dynamically. What is a way of doing it?
First, I wouldn't use document.body. Instead add an empty container:
index.html:
Then opt to only render your
<App />
element:main.js:
Within
App.js
you can import your other components and ignore your DOM render code completely:App.js:
SampleComponent.js:
Then you can programmatically interact with any number of components by importing them into the necessary component files using
require
.You need to pass your components as children, like this:
And then append them in the component's body:
You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:
Sharing my solution here, based on Chris' answer. Hope it can help others.
I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:
Now, I do realize I could also just put
{pushMessages}
and{emailMessages}
directly in myreturn()
below, but assuming I had even more conditional content, myreturn()
would just look cluttered.Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling
ReactDOM.render(<SampleComponent ... />);
With React, you should use SampleComponent directly in the main App.
The content of your Component is irrelevant, but it should be used like this:
You can then extend your app component to use a list.
I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.
https://facebook.github.io/react/index.html