W
W
wakenbyWork2022-02-13 00:13:29
React
wakenbyWork, 2022-02-13 00:13:29

How to conditionally set a class in react?

There are buttons for filtering, and the active button needs to add an active class.

Interface

620820ea11b97646353399.png


I saw that the buttons are taken out to an array of objects and displayed, inside they already throw a class according to the condition, I did the same:

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


Is it right to do so?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew Hecc, 2022-02-13
@wakenbyWork

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>

A
Archi Barrel, 2022-02-13
@Archi88

onClick={() => handleFilter(btn.key)}
className={`shadow-none btn btn-outline-primary ${clazz}`}
activeClassName={'active'}
>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question