|
| 1 | +--- |
| 2 | +name: Rehydrator Interface |
| 3 | + |
| 4 | +menu: API |
| 5 | +route: /api/rehydrator |
| 6 | +--- |
| 7 | + |
| 8 | +# Rehydrator Interface |
| 9 | + |
| 10 | +```javascript |
| 11 | +async (domNode, rehydrateChildren, extra) => <Element /> |
| 12 | +``` |
| 13 | + |
| 14 | +Your rehydrators should be written to this API. |
| 15 | + |
| 16 | +## Contract |
| 17 | + |
| 18 | +Given `domNode`, a rehydrator will return an equivalent React element. |
| 19 | + |
| 20 | +## Parameters |
| 21 | + |
| 22 | +* `domNode`: an element that has matched this rehydrator. |
| 23 | +* `rehydrateChildren`: a function (returning a `Promise`) that can be used to rehydrate any child nodes that contain arbitrary markup. |
| 24 | +* `extra`: page state information, from [`rehydrate()`'s `options` parameter](/api/rehydrate#parameters). |
| 25 | + |
| 26 | +## Return value |
| 27 | + |
| 28 | +A React element that represents `domNode`. |
| 29 | + |
| 30 | +## Example usage |
| 31 | + |
| 32 | + |
| 33 | +`index.js`: |
| 34 | +```javascript |
| 35 | +export { default } from "./SiteHeader"; |
| 36 | +export { default as rehydrator } from "./rehydrator"; |
| 37 | +``` |
| 38 | + |
| 39 | +`rehydrator.js`: |
| 40 | +```javascript |
| 41 | +import Banner from "./Banner"; |
| 42 | + |
| 43 | +export default async (domNode, rehydrateChildren, extra) => { |
| 44 | + const children = await rehydrateChildren(domNode.querySelector(".Banner-children")); |
| 45 | + |
| 46 | + const props = { |
| 47 | + open: !extra.user.hasSeenBanner, |
| 48 | + title: domNode.querySelector(".Banner-title").innerText |
| 49 | + } |
| 50 | + |
| 51 | + return <Banner {...props}>{children}</Banner>; |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +`Banner.js`: |
| 56 | +```javascript |
| 57 | +import React from "react"; |
| 58 | +import PropTypes from "prop-types"; |
| 59 | + |
| 60 | +class Banner extends React.Component { |
| 61 | + static propTypes = { |
| 62 | + children: PropTypes.node, |
| 63 | + hasBeenSeen: PropTypes.bool, |
| 64 | + title: PropTypes.string |
| 65 | + }; |
| 66 | + |
| 67 | + state = { |
| 68 | + open: true |
| 69 | + } |
| 70 | + |
| 71 | + static getDerivedStateFromProps(props, state) { |
| 72 | + // Only show the banner if it hasn't been seen on previous pages, and it |
| 73 | + // hasn't been closed on this page. |
| 74 | + return { |
| 75 | + open: !props.hasBeenSeen && state.open |
| 76 | + }; |
| 77 | + } |
| 78 | + |
| 79 | + render() { |
| 80 | + const { children } = this.props; |
| 81 | + const { open } = this.state; |
| 82 | + |
| 83 | + return <div className={`Banner${open ? " is-open" : ""}`}> |
| 84 | + <h1 className="Banner-title">{title}</h1> |
| 85 | + <div className="Banner-children">{children}</div> |
| 86 | + <button onClick={() => this.setState({ open: false })}>Close banner</button> |
| 87 | + </div>; |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +export default Banner; |
| 92 | +``` |
0 commit comments