Yogesh Chauhan's Blog

How to add a select dropdown in React?

in React on May 13, 2021

HTML vs React select dropdown

There are few differences between HTML and React select dropdown.

This is how we add select dropdown in HTML:



<select>
  <option selected value="react">React</option>
  <option value="angular">Angular</option>
  <option value="vue">Vue</option>
</select>


In the HTML dropdown above, we have “selected” attribute set for the first option so it will be selected automatically.

React does the same thing in a different way.

In React, we need to set “selected” attribute to the main select element.

How is that advantageous over the HTML?

Well, for HTML you need to type code to a specific location to auto select or even change the selection. With React the code stays at the same place so cleaner and nicer way to code.

Another advantage I can think of is that if you’re using a server side language, such as PHP, to add that selected attribute then you need to add the condition to each and every option. You can always come up with a login to reduce the code you write but still it makes a bit messier.

The way React changes the select dropdown using the root element control, the technique is called a controlled component.

React Dropdown Example


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Gap in Flex?CSSDebugging in WordPress Part 3: SCRIPT_DEBUG and SAVEQUERIESWordPressPostgreSQL transactions using the BEGIN, COMMIT, and ROLLBACK statements.PostgresThe Sort and Compare Functions in JavaScriptJavaScript:in-range and :out-of-range selector in CSSCSSSolution to “NullInjectorError: No provider for module” in Angular 9AngularWhat’s the difference between visibility: hidden and display: none?CSSHow to create a dynamic countdown using HTML and JavaScript?HTMLHow to add and remove list items using JavaScript?JavaScriptHow to make a UILabel clickable in Swift 5?SwiftModules and its Core features in JavaScriptJavaScriptWhat is a component helper function in React?React