Created
January 4, 2020 11:17
-
-
Save debonx/1bcc3523431896b1ec6ea0eca053065a to your computer and use it in GitHub Desktop.
React: Container components from presentational components.
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
/* Separating container components from presentational components is a popular React programming pattern. | |
Here’s the basic idea behind it: if a component has to have state, make calculations based on props, or manage any other complex logic, then that component shouldn’t also have to render HTML-like JSX. | |
Instead of rendering HTML-like JSX, the component should render another component. It should be that component’s job to render HTML-like JSX. | |
Following this pattern separates your business logic from your presentational logic. */ | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { GuineaPigs } from '../components/GuineaPigs'; | |
const GUINEAPATHS = [ | |
'1.jpg', | |
'2.jpg', | |
'3.jpg', | |
'4.jpg' | |
]; | |
class GuineaPigsContainer extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { currentGP: 0 }; | |
this.interval = null; | |
this.nextGP = this.nextGP.bind(this); | |
} | |
nextGP() { | |
let current = this.state.currentGP; | |
let next = ++current % GUINEAPATHS.length; | |
this.setState({ currentGP: next }); | |
} | |
componentDidMount() { | |
this.interval = setInterval(this.nextGP, 5000); | |
} | |
componentWillUnmount() { | |
clearInterval(this.interval); | |
} | |
render() { | |
const src = GUINEAPATHS[this.state.currentGP]; | |
return <GuineaPigs src={src} />; | |
} | |
} | |
ReactDOM.render( | |
<GuineaPigsContainer />, | |
document.getElementById('app') | |
); |
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 from 'react'; | |
export class GuineaPigs extends React.Component { | |
render() { | |
const src = this.props.src; | |
return ( | |
<div> | |
<h1>Cute Guinea Pigs</h1> | |
<img src={src} /> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment