WebApps 2
Client side rendering
If the WebApp requires client side functionallity. E.g. trigger events on clicks or collect user input. Opt for the client side rendering option.
Example
Assume the same example WebApp in the index.js example. This example will use hydration for the client step.
// index.js
import * as React from 'react';
import { renderToString } from 'react-dom/server';
...
router.get("/", (req, res) => {
...
// Renders the App component statically
const html = renderToString(<App name={name} />);
res.agnosticRender(html, {
name,
});
});
router.get("/published", (req, res) => {
...
res.json({
date,
});
});
// main.js
import * as React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
export default (initialState, el) => {
/* Update the rendered App component to
include client side functionallity.
E.g. to trigger a request on button click
and display the fetched value.
*/
ReactDOM.hydrate(<App name={initialState.name} />, el);
};
// components/App.js
import * as React from "react";
import PropTypes from "prop-types";
import router from "@sitevision/api/common/router";
// client side SDK
import toasts from "@sitevision/api/client/toasts";
import requester from "@sitevision/api/client/requester";
const App = ({ name }) => {
// function to trigger on button click
const moreInfo = () => {
// send request to the /published route
requester
.doGet({
url: router.getStandaloneUrl("/published"),
})
.then(({ date }) => {
// Display date in a toast
toasts.publish({
ttl: 5,
message: `Last published ${date}`,
});
});
};
// If no client side functionallity included onClick would never trigger
return (
<>
<div className="env-text-h4">Welcome to {name}!</div>
<button
onClick={moreInfo}
className="env-button env-button--primary env-button--large"
>
Latest publish
</button>
</>
);
};
App.propTypes = {
name: PropTypes.string,
};
export default App;
Example result
Welcome to Client side rendering!
Example 2
The same example as above but skipping the server side rendering step, instead opting for only a client side render.
// index.js
...
router.get("/", (req, res) => {
...
res.agnosticRender('', {
name,
});
});
// main.js
import * as React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
export default (initialState, el) => {
// Render the App component
ReactDOM.render(<App name={initialState.name} />, el);
};