Hi aliens 👽, I am here to share most simplest pattern for select input. If you are struggling with select input 😥,confused and facing difficulties to use pure html select input , then this blog is for you my dear. In this blog we are going to discuss controlled input without using any third party library.
lets jump into the code...💻
// App.js
import "./styles.css";
import Dropdown from "./Dropdown";
import { useState } from "react";
export default function App() {
const [selected, setSelected] = useState("Choose One");
return (
<div className="App">
{/* custom dropdown menu */}
<Dropdown selected={selected} setSelected={setSelected} />
{selected}
</div>
);
}
// Dropdown.js
import { useState } from "react";
function Dropdown({ selected, setSelected }) {
const [isActive, setIsActive] = useState(false);
const options = ["React", "Vue", "Angular"];
return (
<div className="dropdown">
<div className="dropdown-btn" onClick={(e) => setIsActive(!isActive)}>
{selected}
<span className="fas fa-caret-down"></span>
</div>
{isActive && (
<div className="dropdown-content">
{options.map((option) => (
<div
onClick={(e) => {
setSelected(option);
setIsActive(false);
}}
className="dropdown-item">
{option}
</div>
))}
</div>
)}
</div>
);
}
export default Dropdown;
Here we are lopping through options array for option tag.
This is fully controlled component
We have create the isActive state for updating the option display if it is false , options will hide , and if it is true we are rendering option , this is simple conditional rendering .
then after we are using onChange event for targeting option value
onChnage we are capturing event , and we are setting event.target.value to selected state
woah ! finish yep so simple to create your own custom controlled select input , hope you like the information , you can also check sandbox link and play around it!😺
https://codesandbox.io/s/custom-dropdown-select-oyisxm
Top comments (0)