I'm making a "filter by category"-type function and for that I need to be able to select multiple options. While I understand that I need to store the selection in the state, I'm hitting a wall when I try to check if the current state already includes the button I am clicking.
Also, pt.II of this question is whether there's a way for the already selected button to "know" whether any of the other buttons have been selected, as the appearance of the buttons need to change depending on whether a single or multiple buttons are selected.
Any help / advice is greatly appreciated.
Code:
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styles from './styles.module.sass';
const Category = (props) => {
const { categories } = props;
const [selected, setSelected] = useState([]);
const handleSelected = (button) => {
if (selected.includes(button)) {
setSelected({ selected: selected.filter((s) => s !== button) });
} else {
setSelected(...selected, [button]);
}
};
return (
<div className={styles.category}>
{categories.map((category) => (
<button
type='button'
key={category.id}
onClick={handleSelected(category.id)}
className={selected.includes(category.id) ? styles.selected : styles.button}
>
{category.name}
</button>
))}
</div>
);
};
Category.defaultProps = {
};
Category.propTypes = {
categories: PropTypes.arrayOf(PropTypes.object).isRequired,
};
export default Category;