Skip to content

Render component only on the server, without "mounting" on the client #6985

Closed
@BowlingX

Description

@BowlingX

Is it possible to have a "frozen" component, that is rendered only on server-side, without being processed on the client side? (without calling the render-cycle again).
Let's say I have a CMS, that statically generates HTML on the server (a legacy system), but I want to use react to render the output inside my component structure.

<Root>
  <ComponentA/>
  <CmsBlock id="staticMarkupId"/>
  <ComponentB/>
</Root>

To prevent the HTML to be exposed twice, I will provide the information only on the server side.
The HTML can be quite big, and I don't want to have them on the client site again.

Right now, I don't see a way to tell react, to prevent calling the render method on a component again.
What I did, is this ugly workaround (react complains about a checksum mismatch though):

/**
 * @flow
 */

import React, { Component, Element } from 'react';

type Props = {
  id:string,
  className?:string
}

type State = {
  markup:Object
}

export default class CmsBlock extends Component<void, Props, State> {

  props:Props;

  state:State;

  constructor(props:Props) {
    super(props);
    const { id } = props;
    const createMarkup = contentId => {
      return {
        __html: global.__CMS_CONTENT__ && global.__CMS_CONTENT__[contentId] ? global.__CMS_CONTENT__[contentId] :
          !global.__CMS_CONTENT__ && global.document ?
            // FIXME: WTF?
            global.document.querySelector(`[data-cms-id="${contentId}"]`).innerHTML :
            `CMS Block ID <strong>${contentId}</strong> does not exist.`
      };
    };

    this.state = {
      markup: createMarkup(id)
    };
  }

  shouldComponentUpdate() {
    // is not called on initial "client-mounting"
    return false;
  }

  render():Element {
    const { className, id } = this.props;
    return (
      <div data-cms-id={id} className={className} dangerouslySetInnerHTML={this.state.markup}/>
    );
  }
}

I used React 15.1.0.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions