#Can I add an interactive react element in .mdx?

4 messages · Page 1 of 1 (latest)

obtuse timber
#

I'm currently using Starlight, I wanted to add a simple checkbox component, for a list. I created a React component and imported into .mdx but it's static upon rendering. The state is not working.

plain helmBOT
#

Hi @obtuse timber. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can add an interactive React component in your .mdx files. However, by default, a UI Framework component is not hydrated in the client. This means its HTML is rendered onto the page without JavaScript, which could be why your component is static upon rendering.

To make your React component interactive, you need to hydrate it using a client:* directive. These are component attributes that determine when your component’s JavaScript should be sent to the browser. For example, you can use client:load to start importing the component's JavaScript when the page loads.

Here's an example of how to use it:

import ReactCounter from '../components/ReactCounter.jsx';

<ReactCounter client:load />

In this example, ReactCounter is a React component that will become interactive once its JavaScript is loaded in the browser.

Remember, the JavaScript framework (React, in this case) needed to render the component will be sent to the browser along with the component’s own JavaScript. If two or more components on a page use the same framework, the framework will only be sent once.

For more information, you can refer to the Astro documentation on hydrating interactive components (https://docs.astro.build/en/guides/framework-components/#hydrating-interactive-components).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@obtuse timber kapa.ai is still learning and improving, please let us know how it did by reacting below