Skip to content

Instantly share code, notes, and snippets.

@threepointone
Last active March 13, 2019 20:09
Show Gist options
  • Save threepointone/4e37155a9cf44b911f976ad5ea85bc33 to your computer and use it in GitHub Desktop.
Save threepointone/4e37155a9cf44b911f976ad5ea85bc33 to your computer and use it in GitHub Desktop.
deep update of text in a react component
import React from 'react'
import { render } from 'react-dom'
// with fiber, we'll be able to write components that update text deep
// inside another string without wrapper dom, or rerendering the whole component
// before
class Lorem extends React.Component {
state = {
str: ''
}
onChange = e => {
this.setState({ str: e.target.value })
}
render(){
return <div>
<input onChange={this.onChange} />
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt {this.state.str} ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore {this.state.str} eu fugiat nulla pariatur.
Excepteur sint occaecat {this.state.str} cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
</p>
</div>
}
}
// after
class Ipsum extends React.Component {
listeners = []
listen = fn => {
this.listeners.push(fn)
}
unlisten = fn => {
this.listeners = this.listeners.filter(x => x!== fn)
}
onChange = e => {
this.listeners.forEach(x => x(e))
}
render(){
return <div>
<input onChange={this.onChange} />
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt <Chunk listen={this.listen}/> ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore <Chunk listen={this.listen} /> eu fugiat nulla pariatur.
Excepteur sint occaecat <Chunk listen={this.listen} /> cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
</p>
</div>
}
}
// The secret sauce here is that components can now return strings
class Chunk extends React.Component {
state = {
str: this.props.initial || ''
}
componentDidMount(){
this.props.listen(e => this.setState({ str: e.target.value }))
}
render(){
return this.state.str
}
}
// render(<Lorem/>, window.root)
render(<Ipsum/>, window.root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment