0

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.

8
  • I think you need to study html first. You need to render options in the beginning Commented Apr 8, 2020 at 23:17
  • i mean when i change the value the event changeValue should work and return the selection but it didn't show the selection i don't know why Commented Apr 8, 2020 at 23:22
  • and I mean you need to render options first. So user has something to pick on the screen. let me post an answer Commented Apr 8, 2020 at 23:24
  • yes i have a selection option which contain all countries name and i put an event onChange the selection value to Albania should the function show the options 1,2 Commented Apr 8, 2020 at 23:28
  • hmm ok, you need to clarify what you are tying to achieve here? Commented Apr 8, 2020 at 23:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i want to show the options 1,2 after the user select Albania in the screen not in the console
this won't work, because the component won't rerender. You should store selectOption1_2 in state
@AdamJeliński that is what I suggested at the end of my answer. But I couldn't add state since OP didnt share the whole component. Thank you for the downvote
0

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>
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.