I
I
Ivan2015-06-18 10:18:52
React
Ivan, 2015-06-18 10:18:52

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")
);

I decided to make the rendering function in the main.js file of the application:
// подключаем компоненты
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();		
});

Now, in order for the component to appear on the page, we write in HTML:
<div class="js-component" component="Select" data-prop="значение свойства 1 "></div>
<div class="js-component" component="Programm" data-id="123"></div>

All this so that I can simply specify a component with parameters in the template, without constantly rewriting JS files.
But the properties already come with a string type from the date attribute. What is the best way to build an application in this case? Maybe I missed something, I tried to find how to implement it, but it didn’t work out. I would be grateful for advice and help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
psyhO_octopus, 2015-07-29
@usyninis

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 question

Ask a Question

731 491 924 answers to any question