Skip to content

Instantly share code, notes, and snippets.

@jneuendorf
Last active August 21, 2017 21:50
Show Gist options
  • Save jneuendorf/0fffd4534a9ea067d0600bef33824110 to your computer and use it in GitHub Desktop.
Save jneuendorf/0fffd4534a9ea067d0600bef33824110 to your computer and use it in GitHub Desktop.
A React component that can more easily be converted between a functional and class component than a React.Component during development
class ConvertibleComponent extends React.Component {
render() {
return this[this.constructor.name](this.props);
}
}
// Lets say you have a component whose final code you aren't certain about yet.
// 1. as functional component:
function MyComponent(props) {
return (
<div name={props.name}>{props.text}</div>
);
}
// 2. as convertible class component
class MyComponent extends ConvertibleComponent {
MyComponent(props) {
return (
<div name={props.name}>{props.text}</div>
);
}
}
// 3. as normal class component
class MyComponent extends ConvertibleComponent {
render() {
return (
<div name={this.props.name}>{this.props.text}</div>
);
}
}
// As you can see the code of the first 2 examples is way more similar than the one of the first and the third:
// Within the class body on the word 'function' is missing (in the 2nd example).
// Thus they are easier to change back and forth.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment