@mdx-js/mdx evaluate(), client-side importing and useState #2070
-
Hey, I'm using mdx to create components, that I would like to evaluate at runtime inside a react component. I'd like to be able to use mdx like this compiled and run in the browser: import { useState } from 'react'
# Here's a button, click it!
export const MyDynamicButton = () => {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>Clicked {count} times!</button>
)
}
Click it! <MyDynamicButton /> But I can't seem to wrap my head around how to import useState from react. I understand that dynamic imports are different when using the Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Depends on where you’re runnign things. This works fine in Node. You can use actual, full, imports. E.g., import Otherwise, you’d have to do bundling. But that comes with a problem: now there’s a react in your bundle. And another React on the outside. And those two Reacts, due to how React works, don’t play together nicely. The easiest way is to rethink your problem: define |
Beta Was this translation helpful? Give feedback.
Depends on where you’re runnign things. This works fine in Node.
react
instead of a URL is a Node (or import map) thing. Outside of Node (or an import map) it doesn’t resolve.You can use actual, full, imports. E.g., import
react
from esm.sh or so.You could investigate import maps, to map
react
to a certain URL.Otherwise, you’d have to do bundling. But that comes with a problem: now there’s a react in your bundle. And another React on the outside. And those two Reacts, due to how React works, don’t play together nicely.
The easiest way is to rethink your problem: define
MyDynamicButton
from outside and pass it in.