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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to calculate elapsed time in JavaScript?JavaScriptWhat’s a Log File and What are Log File Monitors?MiscellaneousHow Do You Make a Private VPN?MiscellaneousHow to check if the page is the home page in WordPress?WordPressclip and clip-path properties in CSSCSSHow get_template_part helps write reusable code in WordPress?WordPressHow to add recaptcha version 3 to PHP website?PHPHow to create a link tag button using CSS?CSSHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPHow Routing works in Angular?AngularWhat does useEffect do in React?ReactThe :last-of-type selectorCSS