const [selectedDepartment, setSelectedDepartment] = useState("");
const DepartmentDropdown = () => {
const handleSelectChange = (event) => {
setSelectedDepartment(event.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(email);
};
return(
<div>
<label htmlFor="departments">Select a Department:</label>
<select
id="departments"
value={selectedDepartment}
onChange={handleSelectChange}
>
<option value="">--Select a Department--</option>
<option value="ai&ds">AI&DS</option>
<option value="cse">CSE</option>
<option value="ece">ECE</option>
<option value="eee">EEE</option>
<option value="it">IT</option>
<option value="mech">MECH</option>
</select>
{selectedDepartment && <p>You selected: {selectedDepartment}</p>}
</div>)
}
Here, I have a doubt where would I use call the function DepartmentDropdown. How to access this dropdown menu. Is there any other easiest way to implement this.
2
Answers
With React function components, you use the name of the function as the component name in JSX, like this:
It looks weird because it’s a function being used as an element name, but that’s how JSX works.
don’t create the state inside your
DepartmentDropdown
component but make it in the parent component from which you will callDepartmentDropdown
as it is shown in the code
handleSelectChange
andselectedDepartment
will be passed as props to theDepartmentDropdown
componentNow in your parent component you create
selectedDepartment
then pass it toDepartmentDropdown
to make it able to show itand create
handleSelectChange
then pass it toDepartmentDropdown
to make it able to updateselectedDepartment
state in the parent component: