Categories
React Answers

How to Fix the “Warning: Use the ‘defaultValue’ or ‘value’ props on select instead of setting ‘selected’ on option” Error Message in React?

Spread the love

Sometimes, we may encounter the “Warning: Use the ‘defaultValue’ or ‘value’ props on <select> instead of setting ‘selected’ on <option>” error message when we’re developing React apps.

In this article, we’ll look at how to fix the “Warning: Use the ‘defaultValue’ or ‘value’ props on <select> instead of setting ‘selected’ on <option>” error message when we’re developing React apps.

Fix the “Warning: Use the ‘defaultValue’ or ‘value’ props on <select> instead of setting ‘selected’ on <option>” Error Message in React

To fix the “Warning: Use the ‘defaultValue’ or ‘value’ props on <select> instead of setting ‘selected’ on <option>” error message when we’re developing React apps, we should set the defaultValue prop to the value attribute value of the default option.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <select defaultValue="">
      <option value="" disabled>
        Choose a salutation ...
      </option>
      <option value="1">Mr</option>
      <option value="2">Mrs</option>
      <option value="3">Ms</option>
      <option value="4">Miss</option>
      <option value="5">Dr</option>
    </select>
  );
}

to set the defaultValue prop to an empty string, which matches the value attribute of the first option.

If defaultValue value matches the value attribute value of an option element, then that one will be selected by default.

This should be used instead of adding the selected attribute onto the option element that we want to select by default.

Conclusion

To fix the “Warning: Use the ‘defaultValue’ or ‘value’ props on <select> instead of setting ‘selected’ on <option>” error message when we’re developing React apps, we should set the defaultValue prop to the value attribute value of the default option.

One reply on “How to Fix the “Warning: Use the ‘defaultValue’ or ‘value’ props on select instead of setting ‘selected’ on option” Error Message in React?”

Leave a Reply

Your email address will not be published. Required fields are marked *