Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Create dropdownlist options from string within react app

I need to display a dropdownlist element with some optgroup labels in my react components.

So I created this method :

 onRenderCategories: any = () => {

        var scope = "";
        var rendu = "";

        for (var scopes in this.props.categories) {
            var ensemble: Array<CategoryTemplateInfos> = this.props.categories[scopes];
            if (ensemble.length == 0) continue;
            scope = ensemble[0].scope;
            rendu += "<optgroup label=" + scope + ">";
            for (var j = 0; j < ensemble.length; j++) {
                var categorie: string = ensemble[j].label;
                var id_categorie: string = ensemble[j].id;
                rendu += "<option value=" + id_categorie+">" + categorie+"</option>";
            }
             rendu += "</optgroup>";
        }
        return rendu;
    }

the output of this method is as excepted ie the html content to put here

 <select >
       <option value="">--Please select a category--</option>
       {this.onRenderCategories()} //here
  </select>

It didn't work!

So how can I fix this issue to convert a string to HTML elements ?

Thanks,

Upvotes: 0

Views: 498

Answers (2)

Shivam Gupta
Shivam Gupta

Reputation: 1238

Try this:

onRenderCategories: any = () => {

    let scope = "";
    let items:JSX.Element[] = [];

    for (var scopes in this.props.categories) {
        let ensemble: Array<CategoryTemplateInfos> = this.props.categories[scopes];
        if (ensemble.length == 0) continue;
        scope = ensemble[0].scope;
        let options = ensemble.map(item => <option value={item.id} key={item.id}>{item.label}</option>)
        let itemstmp = <optgroup label={scope} key={scope}>{options}</optgroup>
        items.push(itemstmp);
    }
    return items;
}


<select >
       <option value="">--Please select a category--</option>
       {this.onRenderCategories()} //here
</select>

Upvotes: 1

Pavel Denisjuk
Pavel Denisjuk

Reputation: 1473

React doesn't work with HTML, it works with JSX, which is only similar to HTML at first glance. In fact it is pure Javascript once JSX is processed by babel.

First of all, you need to invoke your function: {this.onRenderCategories()} - notice the parenthesis - you don't have those in your code. Then, in your categories function you need to switch to actual JSX, and not concat strings because that will not work.

I think the best thing is to go through official React tutorials explaining what React IS and how it works. After you read that, this question will resolve on its own.

So please check out the official documentation :)

Upvotes: 0

Related Questions