Im trying to learn React and am creating a simple dropdown menu thats displays a list of sorting options for a user to choose. Clicking on whichever sort will sort a current HTMl Ul (alphabetical, oldest-newest, etc...)
I have a component called SortSelection that contains the dropdown menu and all the necessary logic to update the ul. Its called like this(inside another component):
<div className="collectionsSortDropdownContainer">
<SortSelection
options={[
{ value: '-publishDate', name: 'Newest' },
{ value: '+publishDate', name: 'Oldest' },
]}
handleSort={this.handleSort.bind(this)}
/>
</div>
Inside SortSelection.jsx
, I currently have it written like this:
const SortSelection = ({
options, extraClass, handleSort,
}) => {
//...necessary logic
However, I realize that I should update SortSelection to be a stateful component since I'll be doing some extra UI stuff like displaying the current value of the Sort and adding a blue checkmark on the user-selected sort.
Im having trouble figuring out how to re-write my component to look like this:
class SortSelection extends Component {
constructor(props) {
super(props);
this.state = {
currentSort: currentSort
};
}
}
while also ensuring that the three necessary data parameters(options, extraClass, handleSort) are passed through for instantiating the component. How can I do this correctly?
SortSelection
You definitely don't need to use a class component for that, functional component will do as well because we have React State Hook
So, in order to make it less complicated for you, just keep using a functional component like you already did:
Just use useState
like so:
const { useState } = require("react")
const SortSelection = ({
options, extraClass, handleSort,
}) => {
const [currentSort, setCurrentSort] = useState(); //<-- useState hook
//...necessary logic
return (
//...JSX
)
}
currentSort
is now a state, and every time you want to change that state and trigger a re-render, use setCurrentSort