Skip to content

Instantly share code, notes, and snippets.

@mutukrish
Created August 18, 2020 02:35
Show Gist options
  • Save mutukrish/02507d8e9e355e7d690f8ed2fca4c6cf to your computer and use it in GitHub Desktop.
Save mutukrish/02507d8e9e355e7d690f8ed2fca4c6cf to your computer and use it in GitHub Desktop.
React Component patterns
const Button = props =>
<button onClick={props.onClick}>
{props.text}
</button>
class ButtonCounter extends React.Component {
constructor() {
super()
this.state = { clicks: 0 }
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({ clicks: this.state.clicks + 1 })
}
render() {
return (
<Button
onClick={this.handleClick}
text={`You've clicked me ${this.state.clicks} times!`}
/>
)
}
}
const UserList = props =>
<ul>
{props.users.map(u => (
<li>{u.name} — {u.age} years old</li>
))}
</ul>
class UserListContainer extends React.Component {
constructor() {
super()
this.state = { users: [] }
}
componentDidMount() {
fetchUsers(users => this.setState({ users }))
}
render() {
return <UserList users={this.state.users} />
}
}
function makeToggleable(Clickable) {
return class extends React.Component {
constructor() {
super()
this.toggle = this.toggle.bind(this)
this.state = { show: false }
}
toggle() {
this.setState(prevState => ({ show: !prevState.show }))
}
render() {
return (
<div>
<Clickable
{...this.props}
onClick={this.toggle}
/>
{this.state.show && this.props.children}
</div>
)
}
}
}
@makeToggleable
class ToggleableMenu extends React.Component {
render() {
return (
<div onClick={this.props.onClick}>
<h1>{this.props.title}</h1>
</div>
)
}
}
class Menu extends React.Component {
render() {
return (
<div>
<ToggleableMenu title="First Menu">
<p>Some content</p>
</ToggleableMenu>
<ToggleableMenu title="Second Menu">
<p>Another content</p>
</ToggleableMenu>
<ToggleableMenu title="Third Menu">
<p>More content</p>
</ToggleableMenu>
</div>
)
}
}
class Toggleable extends React.Component {
constructor() {
super()
this.toggle = this.toggle.bind(this)
this.state = { show: false }
}
toggle() {
this.setState(prevState => ({ show: !prevState.show }))
}
render() {
return this.props.children(this.state.show, this.toggle)
}
}
<Toggleable>
{(show, onClick) => (
<div>
<div onClick={onClick}>
<h1>First Menu</h1>
</div>
{show ?
<p>Some content</p>
: null
}
</div>
)}
</Toggleable>
const ToggleableMenu = props =>
<Toggleable>
{(show, onClick) => (
<div>
<div onClick={onClick}>
<h1>{props.title}</h1>
</div>
{show && props.children}
</div>
)}
</Toggleable>
class Menu extends React.Component {
render() {
return (
<div>
<ToggleableMenu title="First Menu">
<p>Some content</p>
</ToggleableMenu>
<ToggleableMenu title="Second Menu">
<p>Another content</p>
</ToggleableMenu>
<ToggleableMenu title="Third Menu">
<p>More content</p>
</ToggleableMenu>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment