Next.js Discord

Discord Forum

Render a single component without page stuff like html, body and meta tags

Unanswered
Asian swamp eel posted this in #help-forum
Open in Discord
Avatar
Asian swamp eelOP
I am trying to render a single component without all the page stuff in order to use the html inside another website, is this possible?

3 Replies

Avatar
Rafael Almeida
this is very unusual but yeah I think it is possible, you can use renderToStaticMarkup from react-dom/server
I managed to render a simple component using an API Route:
import { NextApiRequest, NextApiResponse } from 'next'
import { renderToString } from 'react-dom/server'

const Component = () => {
  return <div>component rendered in the API Route</div>
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const html = renderToString(<Component />)

  res.setHeader('Content-Type', 'text/html')
  res.send(html)
}
I also tried with the new route handlers in the app dir but next has some safe guards that don't allow the import of react-dom/server