Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS server side async for search engines

I'm rendering my website server side with ReactJS + Router and many of my components make a REST call to generate content. This content won't be send as HTML server side since it's an async call.

A component which could look like this:

import React from 'react'
import ReactDOM from 'react-dom'
// Imports omitted

export default class MyPage extends React.Component {
    constructor() {
        super();
        this.state = {items: []};
            fetch("http://mywebservice.com/items").then((response) => {
                response.json().then((json) => {
                    this.setState({items: json.items})
                }).catch((error) => {});
            });
    }

    render() {
        if (this.state.items && this.state.items.length > 0) {
            var rows = [];
            // Go through the items and add the element
            this.state.items.forEach((item, i) => {
                rows.push(<div key={item.id}></div>);
            });
            return <div>
                    <table>
                         {rows}
                    </table>
            </div>;
        }
        else {
            return <span>Loading...</span>
        }
    }
}

a search engine would index "Loading..." while I obviously want my elements (items) indexed. Is there a way to solve this?

like image 969
ianaz Avatar asked Mar 21 '16 15:03

ianaz


1 Answers

Checkout react-async (https://www.npmjs.com/package/react-async) or react-async-render (https://www.npmjs.com/package/react-async-render)

Sounds like it's just what you need.

like image 137
Yoav Aharoni Avatar answered Sep 30 '22 08:09

Yoav Aharoni