I am not sure why hover applies to all elements when hover on one element.
{isClicked && (
<div className='bg-slate-400 text-white p-6 absolute before: top-7 before: -left-7 flex flex-col gap-2 justify-center'>
{countries.map((country, index) => (
<p
key={index}
className='hover:scale-110 hover:underline'
>
{country}
</p>
))}
</div>)}
So, I changed the style when hover:
<div className='bg-slate-400 text-white p-6 absolute before: top-7 before: -left-7 flex flex-col gap-2 justify-center'>
<h3>All UK</h3>
{countries.map((country, index) => (
<p
key={index}
className='hover: bg-slate-800'
>
{country}
</p>
))}
</div>)}
And now hover applies to all p elements even when I not hover over them.
Why does happens ? What to change so that hover applies only to one element that is hovered on ?
And if a country name contains 2 words, the second word wraps on new row. I kept changing width and height but still happens. I saw on tailwind doc to use whitespace-nowrap but affects all elements and are displayed in a row and not in column all dough flex direction in column.
The whole component:
import React, { useState } from 'react'
const countries = ['England, Scotland, Wales, NorthemIreland']
const Location = () => {
const [loc, setLoc] = useState({country: '', region: ''})
const [isClicked, setIsClicked] = useState('false')
return (
<div
className='text-white relative'
onClick={() => setIsClicked(!isClicked)}
>
Location
{isClicked && (
<div className='bg-slate-400 text-white p-6 absolute before: top-7 before: -left-7 flex flex-col gap-2 justify-center'>
<h3>All UK</h3>
{countries.map((country, index) => (
<p
key={index}
className='hover: bg-slate-800'
>
{country}
</p>
))}
</div>)}
</div>
)
}
export default Location
>Solution :
-
Change
hover: bg-slate-800
tohover:bg-slate-800
-
Make sure the index is unique for every list item, try
console.log(index)
. To check if the item is having unique index. -
To avoid country on longer name going to the next line. Use
whitespace-nowrap
Example:
<div class="before: before: absolute -left-7 top-7 m-4 flex flex-col justify-center gap-2 bg-slate-400 p-6 text-white"> <h3>All UK</h3> <p key="1" class="whitespace-nowrap hover:bg-slate-800">India</p> <p key="2" class="whitespace-nowrap hover:bg-slate-800">Australia</p> <p key="3" class="whitespace-nowrap hover:bg-slate-800">West Indies</p> <p key="4" class="whitespace-nowrap hover:bg-slate-800">SOth America</p> <p key="5" class="whitespace-nowrap hover:bg-slate-800">Very long country name</p> </div>
Output:
The screen shot was captured without the capture of mouse pointer