I am just getting started with React and having difficulty in passing the value of the selected dropdown value to the backend. Sharing the code below for reference, any help would be highly appreciated.
On trying to select a value from dropdown, the following error is being thrown. My end goal is to pass the selected value to the backend on form submit
Error
Cannot read properties of undefined (reading ‘value’)
import React, { useState, useEffect } from 'react'
import Select from 'react-dropdown-select';
import axios from 'axios';
function App() {
const [data, setData] = useState([]);
const [value, setValue] = useState([]);
const [message, setMessage] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(value)
console.log("Selected value:", value);
axios.post("./getEmployeeData", {
value,
}).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
};
useEffect(() => {
fetch("/listEmployees")
.then((response) => response.json())
.then((employee) => {
const parsed = JSON.parse(employee.employeeData);
const employees = Object.entries(parsed).map(([key, value]) => ({
label: value,
value: value
}));
setData(employees);
console.log(parsed, employees);
});
}, []);
return (
<div>
<form onSubmit={handleSubmit}>
<Select
name="select"
options={data}
multi
onChange={(option) => setValue(option.target.value)
}
/>;
<button type="submit"></button>
<div className="message">{message ? <p>{message}</p> : null}</div>
</form>
</div>
)
}
export default App;
2
Answers
there are a couple of corrections and improvements needed to ensure that the react-dropdown-select component works correctly and that the selected values are handled properly. Here’s an updated version of your code with the necessary adjustments:
Make sure to replace "/getEmployeeData" and "/listEmployees" with the actual endpoints in your application. Also, adjust the value assignment in the onChange event based on how your backend expects the selected values to be sent.
There is an error in your code, react-dropdown-select does not use the same event handling as native HTML elements. The onChange handler receives the selected values directly, not an event.
you can use it like this
Not the ‘value’ state has a list of value containing value and label you can extract, then send to api