Skip to content

Instantly share code, notes, and snippets.

@ivtpz
Created March 4, 2017 17:59
Show Gist options
  • Save ivtpz/6ec63206377d4edfc700eaf8825f7108 to your computer and use it in GitHub Desktop.
Save ivtpz/6ec63206377d4edfc700eaf8825f7108 to your computer and use it in GitHub Desktop.
Using ES6 arrow functions and higher order functions to make life easy in React components
// NOTE - this will only run with Babel preset Stage-0 (experimental features)
// Arrow functions as methods is still an experimental Babel feature
// EXAMPLE 1 - Using bind and multiple update functions
class Parent {
constructor() {
this.state = {
name: 'No name yet',
email: 'No email yet'
}
this.updateName = this.updateName.bind(this);
this.updateEmail = this.updateEmail.bind(this);
}
updateName (name) {
this.state.name = name
}
updateEmail (email) {
this.state.email = email
}
}
const parent = new Parent();
class Child {
constructor(props) {
this.props = props
}
updateParentName(name) {
this.props.updateName(name)
}
updateParentEmail(email) {
this.props.updateEmail(email)
}
}
// Emulating passing props from parent to child
let { updateName, updateEmail } = parent;
const child = new Child({updateName, updateEmail});
child.updateParentName('Barney');
console.log(parent.state.name);
child.updateParentEmail('[email protected]');
console.log(parent.state.email);
// EXAMPLE 2 - Using arrow functions and higher order update function
class Parent2 {
constructor() {
this.state = {
name: 'No name yet',
email: 'No email yet'
}
}
update = (prop) => (value) => {
this.state[prop] = value
}
}
const parent2 = new Parent2();
updateName = parent2.update('name');
updateEmail = parent2.update('email');
// NOTE: we are using the same child class as before
// passing in parent methods as "props"
const child2 = new Child({ updateName, updateEmail });
child2.updateParentName('Ernie');
console.log(parent2.state.name);
child2.updateParentEmail('[email protected]');
console.log(parent2.state.email);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment