Warning: Use the ‘defaultValue’ or ‘value’ props on
When working with HTML forms and JavaScript, you may come across a warning in your console regarding the use of the ‘selected’ attribute on the
The Problem
The ‘selected’ attribute is commonly used to preselect an option in a dropdown list. For example:
While this approach works, it can lead to a warning in the console:
Warning: Use the 'defaultValue' or 'value' props on
This warning is raised because setting ‘selected’ on the
Solution 1: Using ‘defaultValue’
The ‘defaultValue’ prop allows us to set the initial value of the
This approach ensures that the desired option is selected by default without raising any warnings in the console.
Solution 2: Using ‘value’
Another way to preselect an option is by using the ‘value’ prop on the
By setting the ‘value’ prop, the corresponding option will be selected by default, and the console warning will not be raised.
Conclusion
When preselecting an option in a dropdown list, it is important to use the ‘defaultValue’ or ‘value’ props on the
Leave a Reply