|
| 1 | +--- |
| 2 | +title: "Isomorphic Rendering" |
| 3 | +description: "Server side rendering of Metal.js components." |
| 4 | +layout: "guide" |
| 5 | +weight: 240 |
| 6 | +--- |
| 7 | + |
| 8 | +<article id="server_rendering"> |
| 9 | + |
| 10 | +## [Server Side Rendering](#server_rendering) |
| 11 | + |
| 12 | +In most cases Metal components will be rendered client side. Let's take the |
| 13 | +following component for example: |
| 14 | + |
| 15 | +```jsx |
| 16 | +import JSXComponent from 'metal-jsx'; |
| 17 | + |
| 18 | +class MyComponent extends JSXComponent { |
| 19 | + render() { |
| 20 | + return <div>{this.props.message}</div> |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +MyComponent.PROPS = { |
| 25 | + message: { |
| 26 | + value: '' |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +export default MyComponent; |
| 31 | +``` |
| 32 | + |
| 33 | +After transpiling/bundling this component, it can be invoked in client side |
| 34 | +JavaScript: |
| 35 | + |
| 36 | +```javascript |
| 37 | +const component = new metal.MyComponent({ |
| 38 | + message: 'Hello, World!' |
| 39 | +}); |
| 40 | + |
| 41 | +// component.element.innerHTML === '<div>Hello, World!</div>' |
| 42 | +``` |
| 43 | + |
| 44 | +Rendering a component this way requires DOM manipulation, and the existence of |
| 45 | +various global variables/utilities that are provided by web browsers. Therefore |
| 46 | +there is no way to render the HTML of this component in a Node.js |
| 47 | +environment without the help of libraries, such as `JSDom`, that emulate client |
| 48 | +functionality. |
| 49 | + |
| 50 | +However, thanks to the `Component.renderToString` method, out of the box server |
| 51 | +side rendering of Metal components is possible in Node.js environments: |
| 52 | + |
| 53 | +```javascript |
| 54 | +const Component = require('metal-component').Component; |
| 55 | +const MyComponent = require('./MyComponent').MyComponent; |
| 56 | + |
| 57 | +const htmlString = Component.renderToString(MyComponent, { |
| 58 | + message: 'Hello, World!' |
| 59 | +}); |
| 60 | + |
| 61 | +// htmlString === '<div>Hello, World!</div>' |
| 62 | +``` |
| 63 | + |
| 64 | +Now all of your custom Metal components can be rendered directly to HTML on the |
| 65 | +server. |
| 66 | + |
| 67 | +</article> |
0 commit comments