Tag: redux

React notes for myself (and for anyone who is interested)

Use bind

Do not do this {() => foo()} while you can do {this.foo.bind(this, bar)} even better you can create a helper to pick up all handler methods and fix the context.

1.) Where is my dispatch

You can always pass down the dispatch method as a prop!
export function mapDispatchToProps(dispatch) {
  return {
 dispatch,
    onLoad: () => {
      dispatch(foo());
    }
  }
}

2.) Nesting

You can do nested elements like:
<Parent>
  {foo.map(item =>
    <Child />
  )}
</Parent>
and within the Parent
return (
<div className=”parent”>{children}</div>
)

 3.) Reducer and Reselect

In the reducer
const reducers = combineReducers({
  fooOne,
  fooTwo,
});
… in the selector (Reselect)
const makeSelectFoo = () => createSelector(
  selectFoo,
¬† (stateFoo) => stateFoo[‘fooOne’][‘bar’]
);

4.) Modifying a child (via cloneElement)

renderChildren() {
  return React.Children.map(this.props.children, child => {
    return React.cloneElement(child, {
      name: this.props.name
    })
  })
}

5.) Destructuring in pure component

const myComponent = ({propertyOne, propertyTwo}) => { //this is instead of (props) then props.propertyOne }

6.) Rest and Spread

const myComponent = ({onClick, ...otherProperties}) => {
//this is instead of (props) then props.propertyOne
<Foo {...otherProperties}>
 <Button onClick={onClick}>Click me</Button>
</Foo>
}
 

Figuring out Object spread (ES2015)

Why is that useful for Redux’s immutable state? I was trying to figure it out then I understood that spread will copy all the enumarable properties in to the new object from the target.

//Enumarable properties
let person = Object.assign({}, {name: 'Joe', age: 12});
console.log(Object.keys(person));

//Non-enumarable property
Object.defineProperty(person, 'profession', {value: 'preacher', enumarable: false});
console.log(person, Object.keys(person));

//Using Object spread to copy enumarable props only
let newObject = {...person, anotherProp: 'Hello'};
console.log(newObject);