React Dynamic Select Menu
First I’ll create a simple React select drop down menu box. Then refactor it to make it dynamic.
To begin, cd to where the app will be located and then use the following command (replacing name with the name of your app) which will create your React app:
npx create-react-app name
Then cd into your app:
To open your app in the browser run the following command:
You should see the revolving React logo in your browser. Inside of the app directory, go to the App.js file. There’s a header tag that contains an image tag responsible for displaying the logo, a paragraph tag with Edit text, and an anchor tag that makes the text Learn React clickable to transfer you to the React website.
I’ll put the select box inside of the header tag above the image tag. I want to present a selection of different swim styles in my menu so first type:
Select a swim style:
Use the select tag to create a selection box:
Now fill the select tag with different selections (also known as options) by listing option tags inside of the select tag. I want my options to include freestyle, backstroke, and butterfly:
Save the App.js file. The browser now displays a select box with freestyle as the first visible option:
Click the down arrow to reveal the other options.
You can add an additional empty option tag at the top of the list of options if you don’t want your select box to automatically show an option:
This is a hardcoded list of styles inside the select tag. Now to refactor the hardcoded list to dynamically fill the select tag with options. Just inside of the App function but outside of the render, create an array containing the swim styles and assign it to the variable styles:
const styles = [“freestyle”, “backstroke”, “butterfly”]
Then map styles to create an option for each style and assign it to the variable optionStyles:
const optionStyles = styles.map((style) =>
Now replace the three option tags for freestyle, backstroke, and butterfly with the single optionStyles:
Test it out by adding another style to your styles array, then saving the file. It will dynamically add the additional style as an option in your select box.
const styles = [“freestyle”, “backstroke”, “butterfly”, “sidestroke”]