Last active
April 2, 2019 19:21
-
-
Save SmolinPavel/118cd5199101ed6c5f0b32d56c933621 to your computer and use it in GitHub Desktop.
Mix of the legacy and new context API
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
import React, { Component, createContext } from 'react'; | |
import PropTypes from 'prop-types'; | |
const ExampleContext = createContext({ api: 'lorem ipsum' }); | |
class New extends Component { | |
static contextType = ExampleContext; | |
render() { | |
const { name } = this.props; | |
const { api } = this.context; | |
return ( | |
<div> | |
<h1>Hello, {name}</h1> | |
<p> | |
This example is using{' '} | |
<span style={{ fontStyle: 'italic', color: 'green' }}>{api}</span> | |
</p> | |
</div> | |
); | |
} | |
} | |
New.propTypes = { | |
name: PropTypes.string.isRequired | |
}; | |
class Legacy extends Component { | |
render() { | |
const { name } = this.props; | |
const { api } = this.context; | |
return ( | |
<div> | |
<h1>Hello, {name}</h1> | |
<p> | |
This example is using{' '} | |
<span style={{ fontStyle: 'italic', color: 'green' }}>{api}</span> | |
</p> | |
</div> | |
); | |
} | |
} | |
Legacy.propTypes = { | |
name: PropTypes.string.isRequired | |
}; | |
Legacy.contextTypes = { | |
api: PropTypes.string | |
}; | |
class Context extends Component { | |
getChildContext() { | |
return { | |
api: 'legacy api that will not be supported in future...' | |
}; | |
} | |
render() { | |
return ( | |
<ExampleContext.Provider | |
value={{ api: 'new api that will be supported in future...' }}> | |
<Legacy name='John Galt' /> | |
<New name='John Galt' /> | |
</ExampleContext.Provider> | |
); | |
} | |
} | |
Context.childContextTypes = { | |
api: PropTypes.string | |
}; | |
export default Context; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment