I'm using Semantic UI React as the front-end framework for a web application I'm building. The application has a horizontal navigation bar that links to the main pages. Several of the main pages also have sub-pages, so I added a Dropdown component to allow direct access to them. However, I was unable to figure out from the Semantic UI React documentation how to handle the event when an item in the Dropdown is selected.
After some searching, I came across Saphie Abayomi's article: Accessing input Values from a Semantic UI React Dropdown, which was extremely helpful in pointing me in the right direction. However, she was using class components and my application uses functional components and hooks. So with a little refactoring, I came up with the following:
First, I defined the items to be included in the Dropdown as an array of objects:
const items = [
{ key: "matches", text: "All Matches", value: "/matches"},
{ key: "preferences", text: "Preferences", value: "/matches/preferences" }
]
The key can be anything unique, it's there so React can keep track of the elements and avoid needless re-renders. The text is what is rendered in the Dropdown and shown to the user. In this case, the value is the route to the view that should be rendered when the user clicks the item in the dropdown.
The next step is to render the dropdown:
return(
<Dropdown
item
text="Matches"
options={items}
onChange={handleDropdown}
/>
);
The key is setting onChange equal to the function that will be called when an item in the Dropdown is selected by the user. The handleDropdown function has two parameters, event and data. The data parameter returns the value from whatever was selected. And without further ado, the handleDropdown function:
const handleDropdown = (event, data) => {
setRedirectURL(data.value);
setDoRedirect(true);
};
For the purposes of my web application, redirectURL and doRedirect are both stored in React's Context, so handleDropdown is setting redirectURL to whatever the value of the item selected by the user was and then setting doRedirect to true to trigger the redirect.
The event parameter isn't particularly useful in my case, so I never read the value. ESLint complains about this, but since I don't have a reason to read it, I don't. Any thoughts on how to solve this minor issue would be appreciated.
Top comments (0)