Answer the question
In order to leave comments, you need to log in
How to conditionally set a class in react?
There are buttons for filtering, and the active button needs to add an active class.
import { useDispatch, useSelector } from 'react-redux'
import { filter } from '../store/todoSlice'
const TodoFilter = () => {
const dispatch = useDispatch()
const activeBtn = useSelector(state => state.todos.keyFilter)
const handleFilter = (key) => {
dispatch(filter({ key }))
}
const listBtns = [
{
name: 'Все',
key: 'all'
},
{
name: 'Выполненные',
key: 'completed'
},
{
name: 'Не выполненные',
key: 'uncompleted'
}
]
return (
<div className='btn-group d-flex mb-3'>
{
listBtns.map(btn => {
let clazz = ''
if (activeBtn === btn.key) clazz = 'active'
return (
<button
onClick={() => handleFilter(btn.key)}
className={`shadow-none btn btn-outline-primary ${clazz}`}
>
{btn.name}
</button>
)
})
}
</div>
)
}
export default TodoFilter
Answer the question
In order to leave comments, you need to log in
You can use a very simple but handy library called classnames .
<button
onClick={() => handleFilter(btn.key)}
className={ classnames('shadow-none', 'btn', 'btn-outline-primary', { active: activeBtn === btn.key }) }
>
{btn.name}
</button>
onClick={() => handleFilter(btn.key)}
className={`shadow-none btn btn-outline-primary ${clazz}`}
activeClassName={'active'}
>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question