How to validate react-select dropdown in React
You may need to validate the react-select dropdown when you are dealing with a react-select dropdown in React. Just as we have created a common component for the input field in the previous article, here we will create a component for the dropdown in React.
Checkout more articles on ReactJS
Demo Application
Steps to validate react-select dropdown in React
1. Create a common Select component
Let’s create a reusable dropdown component using react-select where we will pass all required fields.
Recommended: How to get selected by only value in react-select
Same as the Input field, we have to go through a few more props to handle the validation such as isReq
, errorMsg
, onValidateFunc
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | import React, { memo } from 'react'; import PropTypes from 'prop-types'; import ReactSelect from "react-select"; const changeHandler = (e, props) => { let value = null; if (e) value = e.value; props.onChangeFunc(value, props.name, e); if (!props.onValidateFunc) return; let msg = null; if (!value && props.isReq) { msg = `Please select ${props.title}.`; } props.onValidateFunc(msg, props.name); } const Select = props => { const inputProps = { name: props.name, placeholder: props.placeholder || `Select ${props.title}`, className: props.className, isClearable: props.isClearable, value: props.options.find(x => x.value === props.value), options: props.options } return ( <div className={props.outerClassName}> <label className="form-label">{props.title}</label> <ReactSelect {...inputProps} onChange={e => changeHandler(e, props)} /> {props.errorMsg && <span className="text-danger">{props.errorMsg === true ? `Please select ${props.title}.` : props.errorMsg}</span>} </div> ) } Select.defaultProps = { name: '', title: '', placeholder: '', className: '', outerClassName: 'mb-2', isClearable: true, value: '', options: [], onChangeFunc: () => { }, isReq: null, onValidateFunc: () => { } } Select.propTypes = { name: PropTypes.string, title: PropTypes.string, placeholder: PropTypes.string, className: PropTypes.string, outerClassName: PropTypes.string, isClearable: PropTypes.bool, value: PropTypes.any, options: PropTypes.array, onChangeFunc: PropTypes.func, isReq: PropTypes.bool, errorMsg: PropTypes.any, onValidateFunc: PropTypes.func } export default memo(Select); |
2. Create a form using the Select component
Now it’s time to use the Select component in the main component. First of all, we have to define two different state variables called form
and error
.
In the error state, we have defined the object for each property. The error object contains the following attributes.
isReq
– For require validationerrorMsg
– To render the error message on the screenonValidateFunc
– Function to handle the validation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | const [form, setForm] = useState({ country: null, lang: null }); const onValidate = (value, name) => { setError(prev => ({ ...prev, [name]: { ...prev[name], errorMsg: value } })); } const [error, setError] = useState({ country: { isReq: true, errorMsg: '', onValidateFunc: onValidate }, lang: { isReq: true, errorMsg: '', onValidateFunc: onValidate } }); const onHandleChange = useCallback((value, name) => { setForm(prev => ({ ...prev, [name]: value })); }, []); |
Use the following HTML to render the form in React component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <div className="app"> <div className='mb-3'><strong>Validate react-select dropdown in React - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></strong></div> <div className='form'> <Select name="country" title="Country" value={form.country} options={countryList} onChangeFunc={onHandleChange} {...error.country} /> <Select name="lang" title="Language" value={form.lang} options={languageList} onChangeFunc={onHandleChange} {...error.lang} /> <button className='btn btn-primary btn-sm mt-2' onClick={handleSubmit}> Submit </button> </div> </div> |
Let’s combine all code together and see how it looks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | import React, { useState, useCallback } from 'react'; import Select from './Select'; const countryList = [ { value: "india", label: "India" }, { value: "us", label: "US" }, { value: "australia", label: "Australia" } ]; const languageList = [ { value: "english", label: "English" }, { value: "hindi", label: "Hindi" }, { value: "spanish", label: "Spanish" }, { value: "arabic", label: "Arabic" } ]; function App() { const [form, setForm] = useState({ country: null, lang: null }); const onValidate = (value, name) => { setError(prev => ({ ...prev, [name]: { ...prev[name], errorMsg: value } })); } const [error, setError] = useState({ country: { isReq: true, errorMsg: '', onValidateFunc: onValidate }, lang: { isReq: true, errorMsg: '', onValidateFunc: onValidate } }); const onHandleChange = useCallback((value, name) => { setForm(prev => ({ ...prev, [name]: value })); }, []); const validateForm = () => { let isInvalid = false; Object.keys(error).forEach(x => { const errObj = error[x]; if (errObj.errorMsg) { isInvalid = true; } else if (errObj.isReq && !form[x]) { isInvalid = true; onValidate(true, x); } }); return !isInvalid; } const handleSubmit = () => { const isValid = validateForm(); if (!isValid) { console.error('Invalid Form!'); return false; } console.log('Data:', form); } return ( <div className="app"> <div className='mb-3'><strong>Validate react-select dropdown in React - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></strong></div> <div className='form'> <Select name="country" title="Country" value={form.country} options={countryList} onChangeFunc={onHandleChange} {...error.country} /> <Select name="lang" title="Language" value={form.lang} options={languageList} onChangeFunc={onHandleChange} {...error.lang} /> <button className='btn btn-primary btn-sm mt-2' onClick={handleSubmit}> Submit </button> </div> </div> ); } export default App; |
3. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂
Wow, wonderful weblog layout! How long have you ever been running a blog for? you made blogging look easy. The overall glance of your web site is fantastic, as well as the content!
Thank you so much for your kind words! I’m thrilled that you appreciate the weblog layout and find the content engaging. Stay tuned for more exciting content! 😊✨