This tutorial is on how to create a reusable dropdown list component in React. I broke the functionality down into two components — the actual select dropdown list component and the calling parent/calling component.
The parent component will be App.js and a component called DynamicSelect.js will handle the select list functionality. The entire source code project is on GitHub.
Let’s start with the DynamicSelect component. The DynamicSelect component is the component which will render an array of Seinfeld characters into select list and pass back the selected value via the props object to the parent component. When the onChange event is fired for the select list the event is passed into the handleChange function. This function will pass the selected value back to the parent (App.js) via the props object.
DynamicSelect.js Component
import React, {Component} from 'react';class DynamicSelect extends Component{ constructor(props){ super(props) } //On the change event for the select box pass the selected value back to the parent handleChange = (event) => { let selectedValue = event.target.value; this.props.onSelectChange(selectedValue); } render(){ let arrayOfData = this.props.arrayOfData; let options = arrayOfData.map((data) => <option key={data.id} value={data.id} > {data.name} </option> ); return ( <select name="customSearch" className="custom-search-select" onChange={this.handleChange}> <option>Select Item</option> {options} </select> ) }}export default DynamicSelect;
App.js Component
import React, { Component } from 'react';import logo from './logo.svg';import './App.css';import DynamicSelect from './DynamicSelect';const arrayOfData = [ { id: '1 - Jerry', name: 'Jerry' }, { id: '2 - Elaine', name: 'Elaine' }, { id: '3 - Kramer', name: 'Kramer' }, { id: '4 - George', name: 'George' },];class App extends Component { constructor(props){ super(props) this.state={ selectedValue: 'Nothing selected' } } handleSelectChange = (selectedValue) =>{ this.setState({ selectedValue: selectedValue }); } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Dynamic Select Dropdown List</h1> </header> <p className="App-intro"> <DynamicSelect arrayOfData={arrayOfData} onSelectChange={this.handleSelectChange} /> <br /><br /> <div> Selected value: {this.state.selectedValue} </div> </p> </div> ); }}export default App;
And that’s it. The repository for this code is available on GitHub in this class fashion. This functionatliy can be easily replicated via functional components with hooks as well.