Last active
August 21, 2017 21:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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