Your first React Component in Astro .

ยท

2 min read

I recently built a portfolio, which is aimed to beautiful and functional

Although at first I created all my animation in svelte but to explore native web animation API, I go with Animation API because they are native.

Let's take a ride at what is Astro actually is, it a static site generator that can ship JavaScript on the need to the web, Astro comes with options that enable the developer to control how he wants to load a React, Vue, or svelte component, Let's take an example

Simple Counter React component

import React, { useState } from 'react';

export default function Counter({ children, count: initialCount }) {
  const [count, setCount] = useState(initialCount);
  const add = () => setCount((i) => i + 1);
  const subtract = () => setCount((i) => i - 1);

  return (
    <>
      <div className="counter">
        <button onClick={subtract}>-</button>
        <pre>{count}</pre>
        <button onClick={add}>+</button>
      </div>
      <div className="children">{children}</div>
    </>
  );
}

Now, if we directly import and use this component, then it's not going to be interactive.

---
// Component Imports
import Counter from '../components/Counter.jsx'

// Full Astro Docs
// https://docs.astro.build/core-concepts/astro-components/
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width"/>
  </head>
  <body>
    <main>
      <Counter count={1}>
        <h1>Hello React!</h1>
      </Counter>
    </main>
  </body>
</html>

To make it interactive we can use:-

<Counter count={1} client:visible > // This will load JavaScript Files when Counter is in the Main View.
   <h1>Hello React!</h1>
</Counter>

There are different ways to load your component in Astro, you can [check it out] (docs.astro.build/core-concepts/component-hy..)

ย