Abdul Ahmad
Abdul Ahmad

Reputation: 10021

getting an error when converting react component to string

I've been working with react for a couple months now and I've been doing server side rendering successfully. Recently I started rewriting a personal app with ES6 + Babel. When I try to run renderToString() on a react component I get this error:

renderToString(): You must pass a valid ReactElement.

some code

the component

import React from 'react';
import ReactDOM from 'react-dom';


export class InfoBox extends React.Component {
    render() {
        return (
            <div>
                <div className='info-box'>
                    Hello
                </div>
            </div>
        );
    }
}

if(typeof window !== 'undefined') {
    ReactDOM.render(<InfoBox/>, document.getElementById('info-box-mount-point'));
}

express index route

import express from 'express';
import React from 'react';
import ReactDom from 'react-dom/server';
import InfoBox from '../react-components/info-box/info-box.jsx';

let router = express.Router();
let InfoBoxFactory = React.createFactory(InfoBox);

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { 
        reacthtml: ReactDom.renderToString(InfoBoxFactory)
    });
});

module.exports = router;

another question: should I be saving my components as .jsx or .js? (I'm using jsx in the render method of the component for the html)

Upvotes: 1

Views: 368

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

In this case you need import class InfoBox from info-box.jsx because in info-box.jsx there is no default export

import { InfoBox } from '../react-components/info-box/info-box.jsx';
      ^^^       ^^^

or add default to info-box.jsx,

export default class InfoBox extends React.Component {}
       ^^^^^^^

Update:

You can avoid using createFactory and just render react component, like so

ReactDom.renderToString(<InfoBox />)

Upvotes: 2

Related Questions