wix-incubator / react-templates

Light weight templates for react
https://wix.github.io/react-templates
MIT License
2.82k stars 206 forks source link

Passing state to template #114

Open mikeerickson opened 8 years ago

mikeerickson commented 8 years ago

I am trying to create a simple POC whereby it demonstrates passing props to the template? Does anybody have a sample I can reference which demonstrates using state (and props)

var React    = require('react');
var repeatRT = require('../templates/user-list.rt');

var repeat = React.createClass({
  getInitialState: function () {
    return {
      users: ['One', 'Two', 'Three', 'Four']
    };
  },
  render: repeatRT
});

and here is the template

<div>
    <ul>
        <li rt-repeat="user in this.state.users">{user}</li>
    </ul>
</div>

This is built using webpack... when rendering the page, console produces error that 'cannot read property 'users' of undefined, which leads me to believe there is issue passing along state

mikeerickson commented 8 years ago

Note: My issue seems to be an issue with ES6 classes. When I changed to an ES5 (React.class) it works fine.

nippur72 commented 8 years ago

what ES6 code are you using?

If you have something like this

class Repeat extends React.Component {
    render = require("../templates/user-list.rt");
}

then you need to bind the function:

class Repeat extends React.Component {
    render = require("../templates/user-list.rt").bind(this);
}

Alternatively, you can use this other syntax (not sure if it works with Babel):

class Repeat extends React.Component {
}
Repeat.prototype.render = require("../templates/user-list.rt");
nippur72 commented 8 years ago

EDIT: sorry I was wrong, binding is not necessary because React calls the render() function with the correct this, so it must be something else.

PierBover commented 8 years ago

@nippur72 your third example fixed it for me.

More here.