3

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>
  )
}

1 Answers1

13

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

wassfila
  • 1,173
  • 8
  • 18
  • 1
    @SumitVishwakarma I'm glad it worked for you, if you're happy with the answer, maybe you can select it as the answer to this question post. – wassfila Dec 22 '22 at 10:22
  • Fantastic, what a great answer to the point and worked like a charm – Lauro235 May 24 '23 at 13:10