2.8 KiB
2.8 KiB
id | title | challengeType | isRequired |
---|---|---|---|
5a24c314108439a4d403618d | Render React on the Server with renderToString | 6 | false |
Description
renderToString()
method you can use for this purpose.
There are two key reasons why rendering on the server may be used in a real world app. First, without doing this, your React apps would consist of a relatively empty HTML file and a large bundle of JavaScript when it's initially loaded to the browser. This may not be ideal for search engines that are trying to index the content of your pages so people can find you. If you render the initial HTML markup on the server and send this to the client, the initial page load contains all of the page's markup which can be crawled by search engines. Second, this creates a faster initial page load experience because the rendered HTML is smaller than the JavaScript code of the entire app. React will still be able to recognize your app and manage it after the initial load.
Instructions
renderToString()
method is provided on ReactDOMServer
, which is available here as a global object. The method takes one argument which is a React element. Use this to render App
to a string.
Tests
tests:
- text: The <code>App</code> component should render to a string using <code>ReactDOMServer.renderToString</code>.
testString: getUserInput => assert(getUserInput('index').replace(/ /g,'').includes('ReactDOMServer.renderToString(<App/>)') && Enzyme.mount(React.createElement(App)).children().name() === 'div', 'The <code>App</code> component should render to a string using <code>ReactDOMServer.renderToString</code>.');
Challenge Seed
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div/>
}
};
// change code below this line
Before Test
var ReactDOMServer = { renderToString(x) { return null; } };
After Test
ReactDOM.render(<App />, document.getElementById('root'))
Solution
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div/>
}
};
// change code below this line
ReactDOMServer.renderToString(<App/>);