Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign properties dynamically in React?

Here is a function that has two parameters:

  1. The name of the tag that I want to create
  2. An object that has the properties

Using React, I create a component and render that element to DOM. The problem is that I want to add properties to the element, but it does not allow the loop to set properties within element.

var Element = function(element, properties) {
  var newElement = React.createClass({
    render: function() {
      return (
        React.createElement(element, {}, 'react reuseable')
      );
    }
  });

  ReactDOM.render(React.createElement(newElement, null), document.getElementById('content'));
}

Here is the function call to create a React element:

Element('g', {
  id: 'DrawingController.drawingPathCounter ' + '_shape',
  d: 'path',
  fill: 'none',
  stroke: 'Controllers.TemplateController.wireFrameColour_Selected',
  'stroke-width': 1,
  'class': 'drawingpath',
  pathhover: '',
  'vector-effect': 'non-scaling-stroke'
})
like image 433
Muhammad Asif Javed Avatar asked Oct 31 '22 14:10

Muhammad Asif Javed


1 Answers

You're re-implementing the existing React.createElement method.

You can just store the unique props for your components in an array, then create a list of components using those props.

var propsList = [
  { id: 1, d: 'path', fill: 'none' }, 
  { id: 2, d: 'path', fill: 'none' }, 
  { id: 3, d: 'path', fill: 'none' } 
];

var components = propsList.map(function(props) {
  return React.createElement('g', props);
});

var App = React.createClass({
  render: function() {
    return React.createElement('div', null, components);
  }
});

ReactDOM.render(
  React.createElement(App, null),
  document.getElementById('content')
);

If you want the properties list to be dynamic, then you should store it inside your component's state.

var App = React.createClass({
  getInitialState: function() {
    return {
      propsList: []
    };
  },
  addProps: function(props) {
    var propsList = this.state.propsList.concat([props]);
    this.setState({ propsList: propsList });
  },
  render: function() {
    var components = this.state.propsList.map(function(props) {
      return React.createElement('g', props);
    });

    return React.createElement('div', null, components);
  }
});
like image 75
Dan Prince Avatar answered Nov 12 '22 14:11

Dan Prince