Ad

How To Reuse This Little Block Of Code In React.js?

- 1 answer

I'm a total react Newb, but here is the code I have:

var ExampleComponent = React.createClass({
  getInitialState: function() {
    return {close: false};
  },
  handleClick: function(event) {
    this.setState({close: !this.state.close});
  },
});

  var ButtonThing = React.createClass({
   <ExampleComponent />,
   render: function() {
    <div> yo </div>
    );
  }
 });

Where the "ExampleComponent" can be used in multiple places? I've tried what I have above and just putting in "ExampleComponent" straight, but no luck. Or am I just going about this wrong?

Ad

Answer

Code reuse in react is facilitated by a concept called mixins.

The react docs give a concise example.

For your case

var exampleMixin = {
  getInitialState: function() {
   return {close: false};
  },
  handleClick: function(event) {
    this.setState({close: !this.state.close});
  }
}
var ButtonThing = React.createClass({
  mixins: [exampleMixin], // Use the mixin
  render: function() {
    return (<div> yo </n
  render: function() {
    return (<div> yo </div> );
  }
 });
Ad
source: stackoverflow.com
Ad