How to set a default value in react-select

How to Set a Default Value in react-select

If you are working with React and using the react-select library for dropdowns, you might come across a scenario where you need to set a default value for the select component. In this blog post, we will explore different ways to achieve this.

Method 1: Using the defaultValue prop

The easiest way to set a default value in react-select is by using the defaultValue prop. This prop allows you to set the initial value of the select component.


import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'option1', label: 'Option 1' },
  { value: 'option2', label: 'Option 2' },
  { value: 'option3', label: 'Option 3' }
];

const MySelect = () => {
  return (
    
  );
};

export default MySelect;
  

In this example, we are using the useState hook to create a state variable selectedOption and a function setSelectedOption to update the state. The initial value of selectedOption is set to the first option in the options array. The onChange event handler is used to update the selected option whenever the user makes a selection.

These are the two common methods to set a default value in react-select. Depending on your use case and requirements, you can choose the method that suits you best.

We hope this blog post helped you understand how to set a default value in react-select. If you have any further questions, feel free to ask in the comments below!

Written by: Your Name

Posted

in

by

Tags:

Comments

Leave a Reply

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