Answer the question
In order to leave comments, you need to log in
How to properly render multiple components in a React JS application?
Hello. I'm building an app with gulp + browserify + react + jquery.
Let's say I wrote a "select" component in react that is used multiple times on a page with different properties.
Instead of rendering a component on every div:
React.render(
<Select prop="value1" />,
document.getElementById("select1")
);
React.render(
<Select prop="value2" />,
document.getElementById("select2")
);
...
React.render(
<Select prop="valueN" />,
document.getElementById("selectN")
);
// подключаем компоненты
var components = {};
var app = {}; // сюда помещаются отрендеренные компоненты, правильно ли так ?
components.Programm= require('./programm');
components.CardComments = require('./card');
components.Select= require('./select');
//функция рендеринга компонентов на странице, свойства берутся из атрибутов data-*
function initComponents() {
var components_wrap = document.getElementsByClassName("js-component");
Array.prototype.forEach.call(components_wrap, function(element) {
var c = element.getAttribute("component");
var data = element.dataset;
var component = components[c];
app[c] = React.render(React.createElement(component,data),element);
});
}
// по готовности документа рендерим
$(function() {
initComponents();
});
<div class="js-component" component="Select" data-prop="значение свойства 1 "></div>
<div class="js-component" component="Programm" data-id="123"></div>
Answer the question
In order to leave comments, you need to log in
If it is not possible to completely switch to react, then this option is quite working. Only it is better to transfer the data in one date attribute, so you can stuff JSON there, for example, if the widget data is rendered on the server. Well, adding checks for the presence of a component and other things would also not hurt. Plus, you need to implement a function that would also destroy components. And plus the context parameter. For example, if you open a popup and there are components that need to be drawn, you do not need to run through the entire page, it is enough to search for them only in the popup
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question