Aziz
Aziz

Reputation: 27

Return HTML from react function

I'm new in reactJs I want to return a HTML code from a function

changeValue= (e) =>{
    if(e.target.value=="Albania"){
        return(
            <select>
                <option>1</option>
                <option>2</option>
            </select>
        )
    }
}

render (){

        return(

               <select onChange= {this.changeValue}>
                   {country}
               </select>


        )
    }
}

when I change the select option to Albania the options 1,2 don't show

thank you.

Upvotes: 0

Views: 7402

Answers (2)

Legwan
Legwan

Reputation: 51

You can use State for that.

constructor() {
    this.state = {options: countries};  
}

changeValue = (e) => {
    e.persist();
    if(e.target.value=="Albania"){
        this.setState({options: <><option>1</option><option>2</option></>});
    }
}

render () {
    return (
         <select onChange= {this.changeValue}>
             {this.state.options}
         </select>
    )
}

Upvotes: 0

ilkerkaran
ilkerkaran

Reputation: 4344

You can set it to a variable and render it like {country} something like below;

const selectOption1_2 =null;
changeValue= (e) =>{
    if(e.target.value=="Albania"){
        selectOption1_2 = (
            <select>
                <option>1</option>
                <option>2</option>
            </select>
        )
    }
    else
        selectOption1_2 = null;

}

render (){

        return(

               <select onChange= {this.changeValue}>
                   {country}
               </select>
               {selectOption1_2}


        )
    }
}

it is better to put selectOption1_2 in state tho.

Upvotes: 1

Related Questions