M
M
MarEeeeeee2020-12-19 17:09:16
React
MarEeeeeee, 2020-12-19 17:09:16

How to highlight the active element of a table consisting of div elements?

Hello. There is a plate with some data. By clicking on the field, you want to select it, how to make it so that only one field can be selected at a time?

function FirstWindowItems({item}) {
    function handleClick(item){
        // e.preventDefault();
        console.log(item.FIO, item.position);
      }




    return(
        <div className = "window__items" onClick = {() =>handleClick(item)}>
            {/* <div className = "window__item window__name">{item.id}</div> */}
            <div className = "window__item window__name">{item.FIO}</div>
            <div className = "window__item window__name">{item.position}</div>
            <div className = "window__item window__name">{item.birthDay}</div>
            <div className = "window__item window__name">
                {
                    item.sex ?
                        "М" : "Ж"                    
                }            
            </div>
            <div className = "window__item window__name">{
            item.fired ?
                "Уволен":"Работает"
            }
            </div>            
        </div>
    )
}

I understand that this needs to be done inside the handleClick, but if you just add styles to the block, then more than one element will be selected as a result

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-19
@0xD34F

In parent component:
const [ active, setActive ] = useState(null);

{items.map((n, i) => (
  <FirstWindowItems
    item={n}
    isActive={active === i}
    onClick={() => setActive(i)}
  />
))}

In FirstWindowItems:
function FirstWindowItems({ item, isActive, onClick }) {
  return (
    <div className={`window__items ${isActive ? 'active' : ''}`} onClick={onClick}>
      ...

.window__items.active {
  здесь стили для активного элемента
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question