
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Default Value in Select Using ReactJS
Across web development, the need to produce forms that are dynamic and responsive is a fundamental piece of providing an enjoyable UI/UX. ReactJS, as one of the most popular JavaScript libraries for building User interfaces provides many powerful features for managing form elements. One of these requirements is setting a default value in the dropdown element. This is particularly useful in forms where you would like to preselect an option to prompt the user or some state. In this article, we will discuss how to add a default value in the element of ReactJS and explain them with code snippets for both controlled and uncontrolled components.
Prerequisites
- React Basics: The basic concepts of react components, state management, and hooks. If you have never React and want to use it, read the docs first so you can know what it is (you understand?), then find a beginner course.
- Node.js and npm: Node version 6 or higher, together with NPM (the package manager of the js community), is used to build web-based front-end applications, such as Angular JS apps using Webpack. But, if you already have a node is good. js and npm (node package manager ) into your machine. We can download these by npm install. js website.
- Code Editor: You can use any code editor of your choice on which you are familiar with writing as well as handling this react code.
- React Application Setup: You should have a pre-configured and set React application. If you do not have any, its one line step away from being created using Create React App.
Approaches to Set Default Value in Select
There are two ways to handle a form select element in ReactJS: using useState() and using default value attribute. Both approaches have their own case of uses and is better suited depending on the form's complexity as well as other requirements. The basic understanding of each approach is described below.
- Using useState Hook: The form element's value is stored in the component's state (and updated via event handlers). This provides more control and flexibility, which allows you to render a validation state for the form fields as soon as user input is received on any of them. One good use case where this approach makes sense needs updating displayed text dynamically based on some other field, for example: filter partnership that matches with keyword in title.
- Using useRef Hook: In this approach, we would be setting the value in the default value attribute of the select element. Then using useRef() we would be keeping track of the options selected by the user.
Setting up React Environment
Before diving into the main code you need to be set up with your react environment. If you do not have a react application then create one with 'create-react-app' command. Open terminal/command prompt go to the folder in which you create react application then type below command. This command is used to build the react application at here position.
npx create-react-app select-the-fruits
cd select-the-fruits
Note: You can replace the name 'select-the-fruits' with whatever you want for your project (according to naming conventions).
Set Default value using useState Hook
Controlled components allow you to completely control the form elements by connecting not only just your state with their value but its rendering too. A straight breakdown of the approach is given below: So, here I have taken an example of dropdown list that contains list of fruits in dropdown which is implemented using select in ReactJS. The default value for the select element is set using a controlled component.
import React, {useState} from "react"; // import CSS file for styling import "./App.css"; function App() { // default value const [selectedOption, setSelectedOption] = useState("Apple"); const handleChange = (event) => { setSelectedOption(event.target.value); }; return ( <div className="container"> <h1 className="title">Select Your Favorite Fruit</h1> <select className="styled-select" value={selectedOption} onChange={handleChange} > <option value="Apple">? Apple</option> <option value="Banana">? Banana</option> <option value="Orange">? Orange</option> <option value="Grape">? Grape</option> </select> <p className="result"> You selected: {selectedOption} </p> </div> ); } export default App;
Now, for styling the code add the below-mentioned CSS code in the 'App.css' file in 'src' folder.
/* App.css */ body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; } .container { background-color: #ffffff; padding: 20px 40px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; width: 300px; } .title { font-size: 24px; color: #333333; margin-bottom: 20px; } .styled-select { width: 100%; padding: 10px 15px; border-radius: 8px; border: 1px solid #cccccc; background-color: #ffffff; font-size: 16px; color: #333333; outline: none; transition: all 0.3s ease; } .styled-select:hover { border-color: #888888; } .styled-select:focus { border-color: #007bff; box-shadow: 0 0 8px rgba(0, 123, 255, 0.2); } .result { margin-top: 20px; font-size: 18px; color: #555555; }
Code Explanation
- State Initialization: The useState() initializes the selectedOption state with apple. This is the default selection in dropdown. React is in control of this state to make sure that the value always actually corresponds with whatever we set it as a component's value because;) you know; desperate:request ().
- User Input: The handleChange is an event handler that updates the selectedOption state whenever a different option is chosen by user. The event. target. This will be what we use in the NewDiv class to get out real-time value gets the selected option's matching id and setting an appropriate state.
- Modal Value Binding: The element value becomes bound to our selectedOption state and whenever it changes, we compute a new filtered list. This binding ensures that the dropdown reflects what is in our current state making UI and application logic consistent.This is the Displaying
- Selected Option: The selected option will be displayed on a paragraph tag lying below dropdown, This will give a constant feedback to the user, so it shows what selected fruit in live.
This controlled behavior is especially helpful if you want to poll certain actions corresponding with the option selected, such as form validation or conditional rendering.
Set Default value using useRef Hook
So, in this approach, we would be setting the default value of select using the defaultValue attribute inside the select itself. After that we won't be using useState() for keeping track of the changed value instead we will be using 'ref' for getting the selected value when needed. So in this way, we totally rely on the useRef() instead of useState(), as useRef() directly allows you to access the DOM elements and get the current value of it. The full code of it is given below.
import React, {useRef} from "react"; // Import the CSS file for styling import "./App.css"; function App() { // create a ref to access the select element const selectRef = useRef(null); const handleChange = () => { // Get the selected value from the ref const selectedValue = selectRef.current.value; document.getElementById( "result" // Update the result directly in the DOM ).textContent = `You selected: ${selectedValue}`; }; return ( <div className="container"> <h1 className="title">Select Your Favorite Fruit</h1> <select className="styled-select" defaultValue="Apple" ref={selectRef} onChange={handleChange} > <option value="Apple">? Apple</option> <option value="Banana">? Banana</option> <option value="Orange">? Orange</option> <option value="Grape">? Grape</option> </select> <p id="result" className="result"> You selected: Apple </p> </div> ); } export default App;
Now, for styling the code add the below-mentioned CSS code in 'App.css' file in 'src' folder. The CSS file is the same as that of the above approach
/* App.css */ body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; } .container { background-color: #ffffff; padding: 20px 40px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; width: 300px; } .title { font-size: 24px; color: #333333; margin-bottom: 20px; } .styled-select { width: 100%; padding: 10px 15px; border-radius: 8px; border: 1px solid #cccccc; background-color: #ffffff; font-size: 16px; color: #333333; outline: none; transition: all 0.3s ease; } .styled-select:hover { border-color: #888888; } .styled-select:focus { border-color: #007bff; box-shadow: 0 0 8px rgba(0, 123, 255, 0.2); } .result { margin-top: 20px; font-size: 18px; color: #555555; }
Code Explanation
- This part is uncontrolled since the value of your element doesn't depend on this state (useState). Instead, it uses a ref to access the DOM element directly in order get and set its value when something is selected.
- handleChange() function - Triggers when a user selects any of the options from the dropdown home screen. It uses the ref to get the current value of the element. The value selected in the radio buttons is then taken for use and placed directly into a paragraph element with the id result as content.
- We set the initial text content of those result paragraphs to "You selected: Apple", which matches what our default select option says.
Output
After writing our code, no sooner application is required to run for the output. Once you do that, simply go to the terminal in your VSCode editor and write this command followed up by running the application as shown below. In this repo app is running on port http://localhost:3000/ after performing the above commands.
npm start
The output for the above-mentioned code by both the approaches is mentioned in gif format below.
Conclusion
One of the basic techniques you should know if working with ReactJS is how to set a default value in an element and allow one or more options to be defaulted. By knowing the contrast among both the approaches, you will see how to implement each of them based on your own requisites. Controlled components (useState() approach) are more versatile, and can be applied in such complex forms whereas uncontrolled components (useRef() approach) have a simpler approach to apply in basic form configurations.