Created
November 17, 2018 17:11
-
-
Save sag1v/65044b380dc43200097aadcf77f9f519 to your computer and use it in GitHub Desktop.
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
class App extends Component { | |
state = { | |
showCounter: false, | |
title: 'Whaaa! cool', | |
currentCount: 3 | |
} | |
// create refs so we can pass the element to mount and unmount | |
counterOneRef = React.createRef(); | |
counterTwoRef = React.createRef(); | |
componentDidMount() { | |
// just test another instance of the Counter | |
window.ReactCounter.mount({ title: 'counter two' }, this.counterTwoRef.current); | |
} | |
componentDidUpdate(prevProps, prevState) { | |
const { showCounter, title, currentCount } = this.state; | |
const shouldUpdateCounter = | |
prevState.showCounter !== showCounter || prevState.title !== title; | |
if (shouldUpdateCounter) { | |
if (showCounter) { | |
const counterProps = { | |
title, | |
initialCount: currentCount, | |
onCountUpdate: this.onCountUpdate | |
} | |
window.ReactCounter.mount(counterProps, this.counterOneRef.current); | |
} else { | |
window.ReactCounter.unmount(this.counterOneRef.current); | |
} | |
} | |
} | |
toggleCounter = () => this.setState(({ showCounter }) => ({ showCounter: !showCounter })); | |
onTitleChange = ({ target }) => this.setState({ title: target.value }); | |
onCountUpdate = currentCount => this.setState({ currentCount }); | |
render() { | |
const { title, currentCount } = this.state; | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<div ref={this.counterTwoRef}></div> | |
<img onClick={this.toggleCounter} src={logo} className="App-logo" alt="logo" /> | |
<div ref={this.counterOneRef}></div> | |
<p> | |
This is the main App. | |
</p> | |
<div>{`The count is ${currentCount}`}</div> | |
<input value={title} onChange={this.onTitleChange} /> | |
</header> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment