Hi Devs, in this article, I’m going to show you how to use the Select HTML tag in React JS. As you all know, we use JSX to write HTML in React. Let’s see how we can do this.
- Now, we have an array containing the names of cities. So we render this in Web Page using a map method.
- This is a simple method for using the HTML Select tag. However, we won’t be using this method as it’s considered old school. Instead, we are going to use the Map method.
<select name="cities" id="cities">
<option value="New York">New York</option>
<option value="Chicago">Chicago</option>
<option value="Chicago">Los Angeles</option>
</select>
- The map method in JSX is used to iterate over an array and render a list of elements dynamically.
<select name="cities" id="cities" >
{cities.map((ele, key) => (
<option value={ele} key={key}>
{ele}
</option>
))}
</select>
- In this final step, we will see how to get the current element in an Select tag using the onChange method. The onChange event is triggered when the value of an input element, like a text field or dropdown, changes. It allows you to capture and respond to the new value.
const cities = ["New York", "Los Angeles", "Chicago"]
const handleChange =(e)=>{
console.log(e.target.value)
}
<select name="cities" id="cities" onChange={(e)=>handleChange(e)} >
{cities.map((ele, key) => (
<option value={ele} key={key}>
{ele}
</option>
))}
</select>
Thank you for reading this article. please follow for more articles.
Top comments (0)