I'm trying to use a custom dropdown with a useState
hook. I want to show the list when button is clicked but want to hide when user clicks anywhere outside the button. So, I'm having onClick
events on parent div and button, but the onClick
event of parent div triggers even when clicking the button, preventing the button to show the list.
Here is the code:
import React, { useState } from "react";
export default function App() {
const [showList, setShowList] = useState(false);
return (
<div className="" onClick={() => setShowList(false)}>
<h1>Welcome Here</h1>
<buton onClick={() => setShowList(true)}>Click here</buton>
{showList && (
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
)}
</div>
);
}
And this is the codesandbox example: https://codesandbox.io/s/custom-dropdown-ycq90y?file=/src/App.js:0-426