React – OnChange Event handler on Dynamic Select Component

In this article, we will explore how to create a React select dropdown and attach an onChange event handler to it. We will discuss how to get the selected value from the drop-down child component back to the parent App component. Moreover, we will set the default value of the drop-down from the App js…

By.

•

min read

In this article, we will explore how to create a React select dropdown and attach an onChange event handler to it. We will discuss how to get the selected value from the drop-down child component back to the parent App component. Moreover, we will set the default value of the drop-down from the App js itself in our tutorial.

After following this tutorial, you’ll be able to create a select dropdown list and attach an onChange event handler to it in React. We will also learn how to pass the select box options dynamically as an object to the DropDownSelect to map over all the values dynamically.

What we will have in our tutorial?

  • Create a Reusable DropDownSelect component
  • Get the Selected value from Drop down to the parent App component
  • Set the default value of the drop-down
  • Pass the select option as an array to make the Dropdown component truly reusable.

 

How to Add Onchange Event in Select Box?

You can follow this quick tutorial to create a reusable React Drop down select component and bind the OnChange event:

  • Setting Up a New React App
  • Adding the Bootstrap Library
  • Creating a New Component
  • Configuring the onChange Event Handler
  • Updating the App Component
  • How to Get Select Value from Child to Parent?
  • How to Default Select the DropDown Value?
  • How to Pass Options Array to DropDownSelect Component?
  • Starting the Development Server

 

Setting Up a New React App

First, open your preferred code editor and run the following commands in the terminal to set up a new React application:

npx create-react-app react-dropdown-tutorial
cd react-dropdown-tutorial

 

Adding the Bootstrap Library

To speed up the styling process for our HTML components, we’ll add the Bootstrap library to our React app. Run the following command:

npm install bootstrap

 

Creating a New Component

Create a new file named DropdownSelect.js inside the components folder. This file will contain our React Select component:

import React from 'react';

function DropdownSelect() {
  return (
    <div></div>
  );
}

export default DropdownSelect;

 

Configuring the onChange Event Handler

We’ll use the useState hook to store the selected option’s value. Initially, we’ll pass an empty string as the starting state.

Update the DropdownSelect.js file with the following code:

import React from "react";

const DropdownSelect = () => {
  const [selectedValue, setSelectedValue] = React.useState("");
  
  const handleChange = (event) => {
    const chosenValue = event.target.value;
    setSelectedValue(chosenValue);
  };

  return (
    <div>
      <h2 className="mb-3">React Dropdown Select onChange Example</h2>
      <select onChange={handleChange} className="form-select">
        <option defaultValue disabled>
          Choose a Fruit
        </option>
        <option value="Apple">Apple</option>
        <option value="Grapefruit">Grapefruit</option>
        <option value="Banana">Banana</option>
        <option value="Strawberry">Strawberry</option>
        <option value="Watermelon">Watermelon</option>
      </select>
      {selectedValue && <h2 className="mt-3">{selectedValue}</h2>}
    </div>
  );
};

export default DropdownSelect;

 

Updating the App Component

In App.js, import the Bootstrap CSS and the DropdownSelect component. Update the App function as follows:

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import DropdownSelect from "./components/DropdownSelect";

function App() {
  return (
    <div className="container mt-3">
      <DropdownSelect />
    </div>
  );
}

export default App;

Up to this point you will be able to create a simple Select drop-down event handler in your React js application. As shown below:

 

But in most cases, we create a reusable component like the DropDown one which should emit back the value to the parent component. In the next step, we will convert our implementation in which our DropDownSelect component will send back the selected value as a prop to its parent which is the App component in our case.

How to Get Select Value from Child to Parent?

To display the selected value in the App component, we need to use a callback function to pass the value from the DropdownSelect component to its parent component.

Then pass a callback function as a prop to the DropdownSelect component. Update the App.js file:

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import DropdownSelect from "./DropdownSelect";

function App() {
  const [selectedFruit, setSelectedFruit] = React.useState("");
  const handleFruitSelection = (fruit) => {
    setSelectedFruit(fruit);
  };

  return (
    <div className="container mt-3">
      <DropdownSelect onFruitSelect={handleFruitSelection} />
      {selectedFruit && (
        <h2 className="mt-3">You have selected: {selectedFruit}</h2>
      )}
    </div>
  );
}

export default App;

 

Thereafter, update the DropDownSelect.js file to pass the prop onFruitSelect and update the handleChange event to emit value to parent.

import React from "react";

const DropdownSelect = ({ onFruitSelect }) => {
  const [selectedValue, setSelectedValue] = React.useState("");

  const handleChange = (event) => {
    const chosenValue = event.target.value;
    setSelectedValue(chosenValue);
    onFruitSelect(chosenValue);
  };

  return (
    <div>
      <h2 className="mb-3">
        React Dropdown Select onChange Example - FreakyJolly.com
      </h2>
      <select onChange={handleChange} className="form-select">
        <option defaultValue disabled>
          Choose a Fruit
        </option>
        <option value="Apple">Apple</option>
        <option value="Grapefruit">Grapefruit</option>
        <option value="Banana">Banana</option>
        <option value="Strawberry">Strawberry</option>
        <option value="Watermelon">Watermelon</option>
      </select>
      {selectedValue && <h2 className="mt-3">{selectedValue}</h2>}
    </div>
  );
};

export default DropdownSelect;

 

How to Default Select the DropDown Value?

In case, if we want to display a default selected value in the Drop Down select then we need to pass the default value as prop from a parent. Let’s see how to do it our example.

To set a default value for the selectedFruit state in the App component, you can simply pass a default fruit name as the initial state value when using the useState hook.

Also, pass the selectedFruit prop value to DropDownSelect where it will set as default value.

Update App and DropDownSelect components as shown below:

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import DropdownSelect from "./DropdownSelect";

function App() {
  const [selectedFruit, setSelectedFruit] = React.useState("Apple"); // Added default value
  const handleFruitSelection = (fruit) => {
    setSelectedFruit(fruit);
  };

  return (
    <div className="container mt-3">
      <DropdownSelect
        onFruitSelect={handleFruitSelection}
        selectedFruit={selectedFruit}
      />
      {selectedFruit && (
        <h2 className="mt-3">You have selected: {selectedFruit}</h2>
      )}
    </div>
  );
}

export default App;
import React from "react";

const DropdownSelect = ({ onFruitSelect, selectedFruit }) => {
  const [selectedValue, setSelectedValue] = React.useState(selectedFruit); // Updated default value

  const handleChange = (event) => {
    const chosenValue = event.target.value;
    setSelectedValue(chosenValue);
    onFruitSelect(chosenValue);
  };

  return (
    <div>
      <h2 className="mb-3">
        React Dropdown Select onChange Example - FreakyJolly.com
      </h2>
      <select
        onChange={handleChange}
        className="form-select"
        value={selectedValue}
      >
        <option defaultValue disabled>
          Choose a Fruit
        </option>
        <option value="Apple">Apple</option>
        <option value="Grapefruit">Grapefruit</option>
        <option value="Banana">Banana</option>
        <option value="Strawberry">Strawberry</option>
        <option value="Watermelon">Watermelon</option>
      </select>
      {selectedValue && <h2 className="mt-3">{selectedValue}</h2>}
    </div>
  );
};

export default DropdownSelect;

 

Now will see the default value is selected in Drop Down and its value is also passed at the same time to the parent:

 

How to Pass Options Array to DropDownSelect Component?

To make the DropdownSelect component reusable, you can pass an array of options as a prop and use it to render the dynamic dropdown options.

Then we will pass the fruits array as a prop to the DropdownSelect component.

Thereafter, we will update the DropdownSelect.js component to render the dynamic options using the options prop:

App.js

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import DropdownSelect from "./DropdownSelect";

function App() {
  const fruits = [
    { label: "Apple", value: "apple" },
    { label: "Grapefruit", value: "grapefruit" },
    { label: "Banana", value: "banana" },
    { label: "Strawberry", value: "strawberry" },
    { label: "Watermelon", value: "watermelon" },
  ];

  const [selectedFruit, setSelectedFruit] = React.useState("Apple"); // Added default value
  const handleFruitSelection = (fruit) => {
    setSelectedFruit(fruit);
  };

  return (
    <div className="container mt-3">
      <DropdownSelect
        onFruitSelect={handleFruitSelection}
        selectedFruit={selectedFruit}
        options={fruits}
      />
      {selectedFruit && (
        <h2 className="mt-3">You have selected: {selectedFruit}</h2>
      )}
    </div>
  );
}

export default App;

DropDownSelect.js

import React from "react";

const DropdownSelect = ({ onFruitSelect, selectedFruit, options }) => {
  const [selectedValue, setSelectedValue] = React.useState(selectedFruit); // Updated default value

  const handleChange = (event) => {
    const chosenValue = event.target.value;
    setSelectedValue(chosenValue);
    onFruitSelect(chosenValue);
  };

  return (
    <div>
      <h2 className="mb-3">
        React Dropdown Select onChange Example - FreakyJolly.com
      </h2>
      <select
        onChange={handleChange}
        className="form-select"
        value={selectedValue}
      >
        {options.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
      {selectedValue && <h2 className="mt-3">{selectedValue}</h2>}
    </div>
  );
};

export default DropdownSelect;

Now the DropdownSelect component is truly reusable, as you can pass any array of options to render the dropdown options dynamically. You can also use this component for different sets of options by passing a different array of objects containing label and value properties.

 

Starting the Development Server

Run the following command to start the development server. Once it’s running, the terminal will display URLs that you can use to view your React app in the browser:

npm start

 

Now you can see the React dropdown select component in action. Select a fruit from the list, and the onChange event handler will update the component’s state with the chosen value, displaying it on the screen.

Conclusion

In this tutorial, we have demonstrated how to create a select dropdown and attach an onChange event handler in a React application.

Also, we discussed how to pass the selected value from a reusable DropDownSelect component to its parent. Moreover and important feature to select a default value is also discussed in our example tutorial.

With this knowledge, you can now create custom dropdown menus for your forms and handle user input more effectively.

Leave a Reply

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