const slides = [
[string1, string2, stringi],
[string1, string2, stringi],
[string1, string2, stringi],
[string1, string2, stringi],
];
const changeSlide = (num) => {
const discipline = document.querySelector("#changeSlide-"+num)
discipline.classList.toggle("hidden")
}
return (
<div className="flex flex-col w-1/2 h-60 px-12 py-4 items-center shadow-lg rounded-xl ring-1 ring-black/5">
<h1 className="pb-2">
Technical Skills
</h1>
<ul className="flex space-x-2 border-b-2 mb-2">
<li>
<a href="" className="p-2 inline-block rounded-t-lg hover:bg-gray-200"
onClick={() => changeSlide(0)}>Software</a>
</li>
<li>
<a href="" className="p-2 inline-block rounded-t-lg hover:bg-gray-200"
onClick={() => changeSlide(1)}>Firmware</a>
</li>
<li>
<a href="" className="p-2 inline-block rounded-t-lg hover:bg-gray-200"
onClick={() => changeSlide(2)}>Mechanical</a>
</li>
<li>
<a href="" className="p-2 inline-block rounded-t-lg hover:bg-gray-200"
onClick={() => changeSlide(3)}>DevOps</a>
</li>
</ul>
{slides.map(function(slide, idx) {
return <div className="hidden"
id={"changeSlide-"+idx}
key={idx}>
{slide.map(function(line, jdx) {
return <p key={jdx}>{line}</p>
})
}
</div>
})
}
</div>
)
}
this is what this renders for me
I want this react component to return the strings inside the slides array when the corresponding menu button is clicked. It does that. The problem is that the page seems to render again after the content is displayed. I say may because for all I know it could be rerunning the map function or something else.
I need to 1) find out what and why is happening after changeSlide(idx) is called onClick, and 2) what to do instead.
I am not sure if the above code will run since I deleted a lot of what I am actually using. I thought a simpler view would help. Let me know, and I will repost working code, but this should be best for illustrating the issue. Thanks.
>Solution :
The issue is that the links have a set href, so clicking on it will navigate (to the current page again, as the href is an empty string). Either remove the href, prevent the default action on click, or use another element (perhaps a button) styled to look like a link.
Removing the href:
<a className="p-2 inline-block rounded-t-lg hover:bg-gray-200"
onClick={() => changeSlide(0)}>Software</a>
Using event.preventDefault():
<a href="" className="p-2 inline-block rounded-t-lg hover:bg-gray-200"
onClick={e => {
e.preventDefault();
changeSlide(0);
}}>Software</a>
In addition, it is better to store the selected index in state rather than modifying the DOM manually.