Skip to content

Instantly share code, notes, and snippets.

@sarahsweat
Last active March 27, 2019 16:28
Show Gist options
  • Save sarahsweat/d7cc87c4e18bcf354d247c51a3871a1e to your computer and use it in GitHub Desktop.
Save sarahsweat/d7cc87c4e18bcf354d247c51a3871a1e to your computer and use it in GitHub Desktop.
import React from 'react'
import styled from 'styled-components'
//----------------------------------------------------------------------------------
// Reusable Toggler Component
//----------------------------------------------------------------------------------
class Toggler extends React.Component {
state = {
isToggled: false
}
toggle = () => {
this.setState(state => ({isToggled: !state.isToggled}))
}
render() {
const { isToggled } = this.state
return this.props.children(isToggled, this.toggle)
}
}
//----------------------------------------------------------------------------------
// First Use
//----------------------------------------------------------------------------------
export const First = () => (
<HomeWrapper>
<h1> This is my First Component </h1>
<Toggler>
{(isToggled, toggle) => <ToggledWindow isToggled={isToggled} toggle={toggle}/>}
</Toggler>
</HomeWrapper>
)
const ToggledWindow = ({isToggled, toggle}) => (
<div>
<button onClick={toggle}>Click to toggle</button>
<p>This is toggled {isToggled ? 'ON' : 'OFF'}</p>
</div>
)
//----------------------------------------------------------------------------------
// Second Use
//----------------------------------------------------------------------------------
export const Second = () => (
<HomeWrapper style={{backgroundColor: 'pink'}}>
<h1> This is my Second Component </h1>
<Toggler>
{(isToggled, toggle) => <ToggledWindow2 isToggled={isToggled} toggle={toggle}/>}
</Toggler>
</HomeWrapper>
)
const ToggledWindow2 = ({isToggled, toggle}) => (
<div style={{backgroundColor: isToggled ? 'green' : 'red', color: 'white'}}>
<button onClick={toggle}>Toggle</button>
<p>{isToggled ? 'TOGGLED ON' : 'TOGGLED OFF'}</p>
</div>
)
//----------------------------------------------------------------------------------
// Styled component in both
//----------------------------------------------------------------------------------
const HomeWrapper = styled.div`
height: 200px;
width: 400px;
text-align: center;
background-color: yellow;
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment