Skip to content

Instantly share code, notes, and snippets.

@prigara prigara/App-1.js
Last active Jun 20, 2018

Embed
What would you like to do?
Extract React Component
// Before refactoring
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div className="App">
<button onClick={this.handleClick}>
{this.state.isToggleOn ? "ON" : "OFF"}
</button>
</div>
);
}
}
export default App;
// After the refactoring
import React, { Component } from "react";
import "./App.css";
import { Button } from "./Button";
class App extends Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div className="App">
<Button handleClick={this.handleClick} toggleOn={this.state.isToggleOn}/>
</div>
);
}
}
export default App;
// Extracted React component moved to a different file
import React, { PureComponent } from "react";
import * as PropTypes from "prop-types";
export class Button extends PureComponent {
render() {
return <button onClick={this.props.handleClick}>
{this.props.toggleOn ? "ON" : "OFF"}
</button>;
}
}
Button.propTypes = {
handleClick: PropTypes.func,
toggleOn: PropTypes.bool
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.