Search code examples
reactjsinheritancecomposition

Using Object.assign with React.Component


I pulled this example code together and wanted to see why React is throwing an error. I have hit a wall in trying to explain this as an alternative to using descendants of React.Component.

const App = ({children}) => (
  <div className="app">
    { children }
  </div>
);

const Example = Object.assign(
  {},
  React.Component,
  {
    render () {
      return (
        <h1>Does this work?</h1>
      );
    }
  }
);


ReactDOM.render(
  <App>
    <Example />
  </App>,
  document.querySelector('#target')
);

Solution

  • The below works without createClass or extends

    const Example = (props, context) => Object.assign(
      {},
      Object.create(React.Component.prototype),
      {
        props, context,
        state: {text: 'acutally'},
        render () {
          return (
            <span>This {this.state.text} works</span>
          );
        }
      }
    )