Last active
January 25, 2019 13:53
-
-
Save iamandrewluca/d84fc75d2c51560e094b21593a49019e to your computer and use it in GitHub Desktop.
react-router, composition vs inheritance
This file contains 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
import React from 'react' | |
import { ProtectionConsumer } from './ProtectionContext' | |
import { Link } from 'react-router-dom' | |
// Inheritance | |
export class ProtectedLinkInherited extends Link { | |
render() { | |
return ( | |
<ProtectionConsumer> | |
{({ protected }) => { | |
if (!protected) { return this.props.children } | |
return super.render() | |
}} | |
</ProtectionConsumer> | |
) | |
} | |
} | |
// vs Composition | |
export class ProtectedLinkComposed extends React.Component { | |
render() { | |
return ( | |
<ProtectionConsumer> | |
{({ protected }) => { | |
if (!protected) { return this.props.children } | |
return <Link {...this.props} /> | |
}} | |
</ProtectionConsumer> | |
) | |
} | |
} |
This file contains 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
import React from 'react' | |
import { ProtectionConsumer } from './ProtectionContext' | |
import { Route } from 'react-router-dom' | |
// Inheritance | |
export class ProtectedRouteInherited extends Route { | |
render() { | |
return ( | |
<ProtectionConsumer> | |
{({ protected }) => { | |
if (!protected) { return null } | |
return super.render() | |
}} | |
</ProtectionConsumer> | |
) | |
} | |
} | |
// vs Composition, does not work inside Switch | |
export class ProtectedRouteComposed extends React.Component { | |
render() { | |
return ( | |
<ProtectionConsumer> | |
{({ protected }) => { | |
if (!protected) { return null } | |
return <Route {...this.props} /> | |
}} | |
</ProtectionConsumer> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment