krillov krillov - 25 days ago 7
Node.js Question

How to pass data with server-side rendering to React-component from Node

I'm trying to pass some data to my components. I found this example: http://www.tech-dojo.org/#!/articles/56b1af3e8ff769fc29f96ae8
I have created a class DataWrapper which looks like in the example:

import React, { Component } from 'react'

export default class DataWrapper extends Component {

constructor(props) {
super(props)
}

getChildContext () {
return {
data: this.props.data
};
}

render () {
return this.props.children;
}
}

DataWrapper.childContextTypes = {
data: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.string
]).isRequired
};


Node-server:

app.get('*', (req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
...
const body = renderToString(
<MuiThemeProvider muiTheme={theme}>
<DataWrapper data={'somedata'}>
<RouterContext {...renderProps} />
</DataWrapper>
</MuiThemeProvider>
)
res.render('index', { title, body })


And my component where I want to use the data looks like this:

export default class Template extends Component {

constructor(props, context) {
super(props, context)
console.log("Template context", context.data);
...


context.data is always undefined. What am I missing? Is there an other way to do this?

Answer

If contextTypes is not defined, then context will be an empty object., quoting directly from React Docs. https://facebook.github.io/react/docs/context.html#how-to-use-context

You will need to add

Template.contextTypes = {
    data: // whatever type it is
}