Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnClick event not working for React Component in Astro

I am using a react component for my astro project but the onclick event is not getting called. I am just trying to print link clicked when the link would be pressed, but I can't see any event being called. This is my react component -

import { useState } from "react"
import '../styles/components/tabs.css';

export function Tabs({headings=[], contents=[]}) {
  const [selectedHeading, setSelectedHeading] = useState((headings.length) ? 0 : -1);
  const handleClick  = (index) => {
    setSelectedHeading(index);
  }

  return (
    <div class="tabs" onClick={handleClick}>
      <ul class="tabs-header">
      {headings.map((heading, index) => {
        return <li 
                id={index} 
                style={
                  (selectedHeading === index) ? {color: '#A741FF'} : null
                } 
                onClick={() => console.log('link clicked')}
                >
                  {heading}
                </li>
      })}
      </ul>
      <ul class="tabs-content">
        {
          (selectedHeading === -1) ? null : contents[selectedHeading]
        }
      </ul>
    </div>
  )
}
like image 453
Sumit Vishwakarma Avatar asked Mar 22 '26 22:03

Sumit Vishwakarma


1 Answers

Astro is designed to ship 0 Frameworks javascript by default, therefore, when using a Framework component that has js, you need to set a so-called hydration rule

the .astro component or page where you use your react component should be as follow, using e.g. client:load directive.

---
import InteractiveButton from '../components/InteractiveButton.jsx';
---
<InteractiveButton client:load />

Reference to Astro doc : https://docs.astro.build/en/core-concepts/framework-components/#hydrating-interactive-components

like image 89
wassfila Avatar answered Mar 24 '26 12:03

wassfila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!