Hello All, In this React JS tutorial, We will discuss How to set default value in dropdown using reactjs. In the Previous React JS tutorial, We had discussed How to store form data in local storage using React JS.
In this React JS example, We will take the dropdown list of subjects & will select a default value from the options. We will use react-select npm dependency to demonstrate this example. We will see the step-by-step process to set the default value in the dropdown using reactjs.
So, Let’s start…
Table of Contents
Steps to learn How to set default value in dropdown using reactjs
- Create a new react project
- Install npm dependency
- Create a new form component & include Select for dropdown
- Write dropdown options in constant
- Update App.js
- Run the ReactJS application
Step 1: Create a new React Project
We need to create a new React Project. Use the below command to create a new project in React JS
npx create-react-app myapp
Now, go to our project path
cd myapp
We will open this project in Visual Studio Code editor using the below command.
code .
Step 2: Install npm dependency
Now, We need to install the react-select npm dependency using the following command
npm install react-select
Step 3: Create a new form component & Include Select for dropdown
To create a standard form, We will include form tags. After that, We will use Select to display a dropdown. Please see the following code for your reference.
<form onSubmit={onSubmit}>
<Select
value={subjectOptions.value}
options={subjectOptions}
defaultValue={subjectOptions[3]}
/>
<button type="submit">Submit</button>
</form>
Step 4: Write dropdown options in constant
Now, We will take one constant subjectOptions to display some dropdown options. Please see the below code
const subjectOptions = [
{ value: 'English', label: 'English' },
{ value: 'Maths', label: 'Maths' },
{ value: 'Science', label: 'Science' },
{ value: 'Geology', label: 'Geology' }
];
Full Source Code Form.js
import React, { useState } from "react";
import Select from 'react-select';
const Form = () => {
function onSubmit(e) {
e.preventDefault()
}
const subjectOptions = [
{ value: 'English', label: 'English' },
{ value: 'Maths', label: 'Maths' },
{ value: 'Science', label: 'Science' },
{ value: 'Geology', label: 'Geology' }
];
return (
<>
<div>
<h1>How to set default value in dropdown using reactjs</h1>
<div>
<form onSubmit={onSubmit}>
<Select
value={subjectOptions.value}
options={subjectOptions}
defaultValue={subjectOptions[3]}
/>
<button type="submit">Submit</button>
</form>
</div>
</div>
</>
);
};
export default Form;
Step 5: Update App.js
Now, We will update App.js & include the Form.js component. Please see the below code & update your App.js
import Form from "../src/components/Form";
import "./App.css";
export default function App() {
return (
<>
<div>
<Form />
</div>
</>
);
}
Step 6: Run the ReactJS application
To Run the React Project use the below command
npm run start
Output
