I am building a simple portfolio site.
On the landing page I show images of different projects.
I am mapping over al the projects
{projects.map(({ id, title, route, src }, index) => ())}
What I want is to show the projects name underneath the image when the mouse enters the image.
At the moment when you enter the image it shows al the names underneath al the images.
(because displayTitle
is set to true {displayTitle ? title : null}
)
OnmouseEnter it should only show the hovered image its title.
Any suggestion or creative solutions on how to fix this?
This is the whole component
export const Main = () => {
const [projects, projectsSet] = useState([]);
const [displayTitle, setDisplayTitle] = useState(false);
useEffect(() => {
const projects = projectsLoader();
projectsSet(projects);
}, []);
return (
<>
<NavWrapper>
{projects.map(({ id, title, route, src }, index) => (
<ImageWrapper id={id} key={id}>
<NavLink
activeClassName="active"
className="Nav_link"
exact={true}
to={`/${route}`}
>
<div
onMouseEnter={() => {
setDisplayTitle(true);
}}
onMouseLeave={() => setDisplayTitle(false)}
style={flexStyle}
>
<ProjectImage src={src} alt={title} />
{displayTitle ? title : null}
</div>
</NavLink>
</ImageWrapper>
))}
</NavWrapper>
</>
);
};
I also tried this for the OnMouseEnter
if (index + 1 === id && document.getElementById(id).id) {
if (title.toLowerCase().replace(/\s/g, "") === route) {
setDisplayTitle(true);
}
}
}}
But this understandably has the same effect.
SOLUTION
I am using styled components
export const ProjectWrapper = styled.div`
position: relative;
`;
export const ProjectImage = styled.img`
max-width: 15rem;
max-height: 15rem;
margin: 3rem;
`;
export const Title = styled.div`
display: none;
${ProjectWrapper}:hover & {
display: block;
}
`;
Better use CSS for this. Always render the title you want to show but hide it by default in your stylesheet. Use the :hover
pseudo-selector on the image to show the title on hover.