Reputation: 15
I have a ProjectsSection component in React and an array of project objects. Initially it renders just the first 3 projects. I also have a button which when its clicked all other objects are rendered too.
const showMoreProjects = () => {
if (projectsToShow === 3) {
setProjectsToShow(projects.length)
showBtn.current.innerHTML = 'show less'
} else {
setProjectsToShow(3)
showBtn.current.innerHTML = 'show more'
}
}
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
{
projects.slice(0, projectsToShow).map(project => <Project key={project.title} details={project} />)
}
</div>
<button ref={showBtn} onClick={showMoreProjects}>view more</button>
Here is the Project component
<div ref={project} className="project relative w-full h-64 bg-gray-800 rounded-lg bg-cover bg-center overflow-hidden"
style={{ backgroundImage: `url(${details.imgUrl})` }}>
<div className="w-full h-full flex justify-center items-center">
<div className="project-card-hover opacity-0 hover:opacity-100 transition-opacity duration-300 ease-in-out w-full h-full">
<div className="w-full h-full flex flex-col justify-center items-center bg-black bg-opacity-50">
<h1 className="text-4xl text-white mb-8">{details.title}</h1>
<div className="w-1/2 flex justify-around items-center text-white text-2xl">
<a href={details.link} target="_blank" rel="noopener noreferrer"><FontAwesomeIcon icon={faLink} /></a>
<a href={details.github} target="_blank" rel="noopener noreferrer"><FontAwesomeIcon icon={faGithub} /></a>
<a href={details.play} target="_blank" rel="noopener noreferrer"><FontAwesomeIcon icon={faPlay} /></a>
</div>
</div>
</div>
</div>
</div>
When more projects are shown, browser auto scrolls down to the last components rendered! Can that be prevented?
Upvotes: 1
Views: 349
Reputation: 78900
The default behavior of a button when there's a mouse down event is to give it focus. This may be causing the scrolling behavior as you supposed. To avoid this default behavior, you can place your event handler on the mousedown
event instead of click
and call the event's preventDefault
method:
const showMoreProjects = (event) => {
event.preventDefault();
if (projectsToShow === 3) {
setProjectsToShow(projects.length)
showBtn.current.innerHTML = 'show less'
} else {
setProjectsToShow(3)
showBtn.current.innerHTML = 'show more'
}
}
// ...
<button ref={showBtn} onMouseDown={showMoreProjects}>view more</button>
Upvotes: 2