0

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?

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I've missed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.