JavaScript React

Set a Default Value for a React Select Element

Spread the love

We can set the default value of a React select element by using the useState hook.

The default value can be set as the default value of the hook. Then we can set it as the value of the value prop of the select element.

For instance, we can write:

import React, { useState } from "react";

const fruits = ["orange", "apple", "grape"];

export default function App() {
  const [fruit, setFruit] = useState("apple");
  return (
    <div className="App">
        onChange={e => setFruit(fruits[])}
        { => (
          <option value={f}>{f}</option>

We set the value prop to fruit so that we set the initial value of it.

We map the fruits entries to the option elements.

Then we add an onChange handler to call setFruit as we change selection.

We get the selected value from the fruits array by writing:


so that we get the string given the index of the selected option.

Then we display the selected value so that we can see what we selected below the select element.

Since we set the initial value of the fruit state to 'apple', that’s what we display when we load the select element, which means that it’s the default value.

Now we can have default values for our React select elements.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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