Ad

React Render Component Multiple Times In Container With Different Props?

- 1 answer

I am trying to create a reusable "tag" React component, so that users can create tags onclick and see that information displayed in the DOM.

Here's the module:

module.exports = React.createClass({
  render: function() {
    return (
      <div className="language chip" data-lang={this.props.language} data-lang-level={this.props.level}>
        {this.props.language} ({this.props.level})
        <i className="material-icons">close</i>
      </div>
    );
  }
});

And the onclick call:

var addLanguage = $('a#add-language');
addLanguage.click(function() {
  var languageLearning = $('#language-learning');
  var levelLearning =  $('#language-level');

  if (languageLearning != null && levelLearning != null) {

    ReactDOM.render(
      <LanguageChip
        language={languageLearning.val()}
        level={levelLearning.val()}
      />,
      document.getElementById('language-chips')
    );

    languageLearning.select2('val', '');
    levelLearning.select2('val', '');

  }
})

I didn't realise that when using React.DOM, "Any existing DOM elements inside are replaced when first called." This means when adding a second chip, the first is removed. I want users to be able to have multiple chips.

How can I do this?

Ad

Answer

I don't know if you've got a good reason to not add the form used to create a tag on your component, but it would be much simpler if you could. Then you just have to add your tags on an array and display them with your LanguageChip component.

I've made an example here: https://jsfiddle.net/snahedis/69z2wepo/28193/

I don't know what's your level of understanding of React so if something isn't clear let me know :)

Edit: the same example inside a preexistent form: https://jsfiddle.net/snahedis/69z2wepo/28217/

Ad
source: stackoverflow.com
Ad