Muhammad Asif Javed
Muhammad Asif Javed

Reputation: 165

Can we add state name dynamically in react

Getting the object from the dataBase and after that i am converting it to array to change the state of the rect component and now i want to update the data to my view that i have created in react.

the method i am following is as under:

var PreviewContainer = React.createClass({
  getInitialState: function() {
    return {
      sourceImg: {
        src0: 'xyz',
        src1: 'xyz',
        src2: 'xyz',
        src3: 'xyz'
      },
      id: '',
      alter: "myalt"
    };
  },
  render: function() {
    Interfaces.previewContainer = this;
    var imgContainer = [];

    for (var i = 0; i < 4; i++) {
      imgContainer.push(React.createElement(PreviewImgContainer, {
        key: i,
        sourceImg: this.state.sourceImg['src' + i],
        alter: this.state.alter
      }));
    }
    return (
      React.createElement('div', {
          className: 'previewContainer'
        },
        imgContainer,
        React.createElement(ColorCardParent))
    );
  }
});

and after that i have to set these imagaes in the container as follows way using static methods

Interfaces.previewContainer.setState({sourceImg: {
    src0: templatearray[0].image_path.slice(1),
    src1: templatearray[1].image_path.slice(1),
    src2: templatearray[2].image_path.slice(1),
    src3: templatearray[3].image_path.slice(1)
  }
});

Is there a way to do this so that i can just do this dynamically.

Upvotes: 0

Views: 1113

Answers (1)

wintvelt
wintvelt

Reputation: 14101

Not quite clear what you are trying to achieve and what the issue is, but you could fill your sourceImg object as follows:

var sourceImg = {};
for (var i=0; i<templatearray.length; i++) {
  var srcKey = "src" + i.toString();
  sourceImg[srcKey] = templatearray[i].image_path.slice(1);   // fill object dynamically
}
Interfaces.previewContainer.setState({ sourceImg : sourceImg });

BTW: Dynamically filling an object is unrelated to react.

Upvotes: 1

Related Questions