How to use React component in vitepress #2183
-
How to use React component in vitepress? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 2 replies
-
Will be great to have an example in the docs - Evan says it's possible : https://twitter.com/youyuxi/status/1377414690997870592?lang=en |
Beta Was this translation helpful? Give feedback.
-
<div ref="el" />
<script setup>
import { createElement } from 'react'
import { createRoot } from 'react-dom/client'
import { ref, onMounted } from 'vue'
import FooBar from './FooBar'
const el = ref()
onMounted(() => {
const root = createRoot(el.value)
root.render(createElement(FooBar, {}, null))
})
</script> |
Beta Was this translation helpful? Give feedback.
-
Hey @brc-dd, I am going through your example. I extended it a bit by using the external react library like shoelace here is the demo for the same https://stackblitz.com/edit/vite-khbbjq. While running the app in the dev with Can you please help here! |
Beta Was this translation helpful? Give feedback.
-
Any way to use React with Typescript? Looks like vite bundler needs to do this, but I'm not sure how. BTW Any similar alternatives to Vitepress in React world? I really love the design and devex of Vitepress |
Beta Was this translation helpful? Give feedback.
-
This is how I've been doing to document my react components.
// page.md
## Alert Dialog
<div ref="alertDialog" />
## Disabled Dialog
<div ref="disabled" />
<script setup>
import { ref, onMounted } from 'vue'
import {AlertDialog, DisabledDialog} from '../_components/demo/alertDialog-demo.tsx'
import {createReactApp, createPortalNode} from '../_components/createReactApp.ts'
const alertDialog = ref()
const disabled = ref()
onMounted(() => {
createReactApp([
createPortalNode(AlertDialog, alertDialog.value),
createPortalNode(DisabledDialog, disabled.value, {isDisabled: true}),
])
})
</script>
// createReactApp.ts
import React from 'react'
import {createRoot} from 'react-dom/client'
import {createPortal} from 'react-dom'
export const createReactApp = (children: React.ReactNode) => {
const root = createRoot(document.createElement('div'))
root.render(children)
}
export const createPortalNode = (component: React.FC, targetElement: Element, props: React.ComponentProps<any>) => {
if(!targetElement) {
console.warn('Target DOM node is not specified for Portal')
return null
}
return createPortal(React.createElement(component, props), targetElement)
} |
Beta Was this translation helpful? Give feedback.
https://stackblitz.com/edit/vite-dnqmyv