Home > Software design >  Change inner div on hover in react grid tailwind
Change inner div on hover in react grid tailwind

Time:02-05

So, for CSS I am using tailwindcss. I have implemented integer based approach but when I hover quickly over the divs, the state remains un updated. If the value is 0, the first div is shown else the second div is shown. Below is the code :

 <div className="text-white m-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 grid-flow-row gap-8">
            {
                data.map((d,idx)=>(
                <div onm ouseEnter={()=>{toggleState(idx,1)}} onm ouseLeave={()=>{toggleState(idx,0)}} key={'event' idx} className="relative h-96 overflow-hidden" style={{background: "-webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 1))), url('https://images.unsplash.com/photo-1475855581690-80accde3ae2b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80') no-repeat",backgroundSize:'cover'}}>
                    {!v[idx] && (
                        <div className="absolute w-full py-2.5 bottom-0 inset-x-0 text-white text-center leading-4">
                            <div className='divide-y-2 px-2 h-full'>
                                <h2 >{d.title}</h2>
                                <p >{d.dueDate}</p>
                            </div>
                        </div>
                    )}
                    {v[idx] && (
                             <div className="absolute w-full py-2.5 text-white text-center leading-4">
                                <div className='px-2 w-full'>
                                    <h2 >{d.title}</h2>
                                    <p >{d.desc}</p>
                                    <span className='bottom-0 right-0'>Go to Course =</span>
                                    {/* <a href="#" className='align-bottom'>Go to the Course</a> */}
                                </div>
                            </div>
                    )}
                </div>
                ))
            }
    </div>

The function for toggle state

const [v,setV] = useState([0,0,0,0,0,0,0]);
      const toggleState = (idx,value)=>{
        const newV = [...v];
        newV[idx]=value;
        setV(newV);
      }

What is the best way to implement such utility?

CodePudding user response:

It is hard to give you the best help given the out of context snippet of code you gave. But to improve the UX and the performance of your interaction you could avoid to handle all that in the list.

You could start isolating the components of the list and handle the mouse in/out in the single component.

Something like this:

<div>
       {data.map((d,idx)=> <YourComponent d={d} />}
</div>

YourComponent:

function YourComponent(props) {

return (
 <div onm ouseEnter={...} onm ouseLeave={...} >
  ...
 </div>
)}

This way every single component would handle itself and the list will not re-render on every mouse move.

  •  Tags:  
  • Related