HackDash

Node.js preact-render-to-string Render JSX and Preact components to an HTML string.

Works in Node & the browser, making it useful for universal/isomorphic rendering.

>> Cute Fox-Related Demo (@ CodePen)

Render JSX/VDOM to HTML

import render from 'preact-render-to-string'; import < h>from 'preact'; /** @jsx h */ let vdom = 
class="foo">content
; let html = render(vdom); console.log(html); //
content

Render Preact Components to HTML

import render from 'preact-render-to-string'; import < h, Component>from 'preact'; /** @jsx h *//* w w w . d e m o 2s . c om */ // Classical components work class Fox extends Component < render(< name>) < return class="fox">< name>; > > // . and so do pure functional components: const Box = (< type, children>) => ( 
class=`>> ); let html = render( "open"> name="Finn" /> ); console.log(html); //
Finn

Render JSX / Preact / Whatever via Express!

import express from 'express'; import < h>from 'preact'; import render from 'preact-render-to-string'; /** @jsx h */// w w w . d e m o 2 s. c o m // silly example component: const Fox = (< name>) => ( 
class="fox">
< name>

This page is all about name>.

); // basic HTTP server via express: const app = express(); app.listen(8080); // on each request, render and return a component: app.get('/:fox', (req, res) => < let html = render(name= />); // send it back wrapped up as an HTML5 document: res.send(`$ `); >);

License

The repository of preact-render-to-string is in Gitgithub.com/developit/preact-render-to-string

Читайте также:  Php парсер html страниц

Install Command

To install preact-render-to-string use the following command:

npm i preact-render-to-string

More Examples

The following examples shows how to use Node.js library preact-render-to-string.

const h = require('preact-hyperscript-h'); const render = require('preact-render-to-string'); // This will be rendered statically module.exports = render(h.html([ h.head([ h.title('koa-es-modules-rollup'), ]), h.body([ // This loads './app.js' from server as an ES6 Module bundled with all its dependencies using Rollup h.script(< src: 'app.js'>) ]), ]));
var express = require('express') var request = require('request') var app = express() var h = require('preact').h; var render = require('preact-render-to-string'); app.get('/', function (req, res) < request('http://localhost:8080', function (error, response, body) < var data = JSON.parse(body); var cities = [] for (var item in data) < cities.push(data[item].Name)/* w w w . d e m o 2s . c o m*/ > var City = function City(_ref) < var name = _ref.name; return h( "div", < "class": "city">, h( "strong", null, name ) ); >; var cityDivs = cities.map(function (name, i) < return h(City, < name: name>); >); var html = render(h( "div", null, cityDivs )); res.send('' + html) >); >) app.listen(3000)
const render = require('preact-render-to-string') const decache = require('decache') const path = require('path') const defaultOptions = // w w w . d e m o 2 s . c o m cache: true, doctype: '' > function clearRequireCache (entries) < for (let i = 0; i < entries.length; i += 1) < decache(entries[i]) >> function compileLayout (Element, context, options) < const layoutPath = path.join(options.layoutPath, options.layout) const LayoutElement = require(layoutPath) const Layout = LayoutElement.default || LayoutElement if (!options.cache) < clearRequireCache([options.filename, layoutPath]) >return `$$Element(context)>))>` > exports.compile = (template, compileOptions) => (context) => < const options = Object.assign(defaultOptions, compileOptions) const ViewElement = require(options.filename) const Element = ViewElement.default || ViewElement if (typeof options.beforeRender === 'function') < options.beforeRender() >if (options.layout) < return compileLayout(Element, context, options) > if (!options.cache) < clearRequireCache([options.filename]) >return `$$Element(context))>` >
import render from 'preact-render-to-string' export default (rootComponent, initialState) => `    name="viewport" content="width=device-width, initial-scale=1"> html, body "root">$    `

  • Node.js queoid There are few ways to get help:
  • Node.js listr-update-renderer These options should be provided in the Listr options object.
  • Node.js listr-silent-renderer MIT ??
  • Node.js preact-render-to-string Render JSX and Preact components to an HTML string.
  • Node.js mobiledoc-text-renderer This is a Text renderer for the Mobiledoc format used by Mobiledoc-kit.
  • Node.js preact-render-to-json Render JSX and Preact components to JSON.
  • Node.js pkghub-render A renderer for pkghub, render html as given module/template template.

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

How to render a React element to an HTML string?

What happens when you want to render a React string or element to an HTML string? For some reasons, you may want to have the generated HTML string from your React component instead of a mounted component and render it on the page.

If you want to render an HTML String for SSR purposes, you may consider using a framework like Next.js instead of manually rendering a React string to HTML. Using a framework like Next.js can offer a wide range of features and tools for building server-rendered applications like abstracting away a lot of the complexity of setting up server rendering, automatic code splitting, significant performance improvements, . etc.

What is ReactDOMServer?

The ReactDOMServer module is a part of the official React library. It provides methods for rendering React components to static HTML. It’s useful for server-side rendering, where you want to generate HTML on the server and send it to the client.

Converting a React String to an HTML String

To convert a React string to an HTML string, we need to use the renderToString method provided by ReactDOMServer. The renderToString method takes a React component as an argument and returns a string of HTML.

Here is an example of how to use the renderToString method to convert a React string to an HTML string:

import React from 'react'; import ReactDOMServer from 'react-dom/server';  const reactString = '
Hello, world!
'
;
const htmlString = ReactDOMServer.renderToString(React.createElement('div', dangerouslySetInnerHTML: __html: reactString > >)); console.log(htmlString); // Output:
Hello, world!

In this example, we are using React.createElement to create a React element with the dangerouslySetInnerHTML prop set to < __html: reactString >. The dangerouslySetInnerHTML prop is used to render HTML directly to the page. Then, the ReactDOMServer.renderToString function convert the React element to an HTML string.

Here is another example but with a custom component you already created before. This example convert a JSX to string.

import  renderToString > from 'react-dom/server'  renderToString(YourAwesomeComponent props1="value1" props2= value: '2' >> />) 

The renderToString function can be used on both server-side and client-side. If you want to render all page server-side for SEO or UX purposes for example, you can use the ReactDOMServer.renderToNodeStream function to improve your load time or the ReactDOMServer.renderToPipeableStream in newer React versions. You can find an example for this last method on the renderToPipeableStream Documentation.

More informations on the React documentation.

If you’re seeking solutions to a problem or need expert advice, I’m here to help! Don’t hesitate to book a call with me for a consulting session. Let’s discuss your situation and find the best solution together.

Источник

preact-render-to-string

Render JSX and Preact components to an HTML string.

Works in Node & the browser, making it useful for universal/isomorphic rendering.

Render JSX/VDOM to HTML

import  render > from 'preact-render-to-string'; import  h > from 'preact'; /** @jsx h */ let vdom = div class="foo">content/div>; let html = render(vdom); console.log(html); // 
content

Render Preact Components to HTML

import  render > from 'preact-render-to-string'; import  h, Component > from 'preact'; /** @jsx h */ // Classical components work class Fox extends Component  render( name >)  return span class="fox">name>/span>; > > // . and so do pure functional components: const Box = ( type, children >) => ( div class=`box box-$type>`>>children>/div> ); let html = render( Box type="open"> Fox name="Finn" /> /Box> ); console.log(html); // 
Finn

Render JSX / Preact / Whatever via Express!

import express from 'express'; import  h > from 'preact'; import  render > from 'preact-render-to-string'; /** @jsx h */ // silly example component: const Fox = ( name >) => ( div class="fox"> h5>name>/h5> p>This page is all about name>./p> /div> ); // basic HTTP server via express: const app = express(); app.listen(8080); // on each request, render and return a component: app.get('/:fox', (req, res) =>  let html = render(Fox name=req.params.fox> />); // send it back wrapped up as an HTML5 document: res.send(`$html>`); >);

Error Boundaries

Rendering errors can be caught by Preact via getDerivedStateFromErrors or componentDidCatch . To enable that feature in preact-render-to-string set errorBoundaries = true

import  options > from 'preact'; // Enable error boundaries in `preact-render-to-string` options.errorBoundaries = true;

Suspense & lazy components with preact/compat & preact-ssr-prepass

npm install preact preact-render-to-string preact-ssr-prepass
export default () =>  return h1>Home page/h1>; >;
import  Suspense, lazy > from 'preact/compat'; // Creation of the lazy component const HomePage = lazy(() => import('./pages/home')); const Main = () =>  return ( Suspense fallback=p>Loading/p>>> HomePage /> /Suspense> ); >;
import  render > from 'preact-render-to-string'; import prepass from 'preact-ssr-prepass'; import  Main > from './main'; const main = async () =>  // Creation of the virtual DOM const vdom = Main />; // Pre-rendering of lazy components await prepass(vdom); // Rendering of components const html = render(vdom); console.log(html); // 

Home page

>; // Execution & error handling main().catch((error) => console.error(error); >);

Источник

Jsx to html string

Convert jsx to html string

  • recast: JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
  • chai: BDD/TDD assertion library for node.js and the browser. Test framework agnostic.
  • eslint: An AST-based pattern checker for JavaScript.
  • jsdoc-to-markdown: Generates markdown API documentation from jsdoc annotated source code
  • mocha: simple, flexible, fun test framework

Convert JSX element in ecmascript code string to double quoted html string in the code. Forked from angular-jsx https://github.com/thesam/angular-jsx

Kind: global function
Returns: string — double quoted html strings converted from JSX element in ecmascript.

Param Type Description
code string jsx element contained in ecmascript code string.
let jsxHtml = require('jsx-html');
let code = 'let template =
hello
'
jsxToHtml(code)
// returns 'let template = "
hello
"'

Источник

Оцените статью