React guide

Date: May 25, 2017

Category : js, react

General tips and pointers to keep in mind while writing react apps.

Conditioning:

Always use && conditioning in case of ‘if’.

  {/* In this case if isAdmin is false the next JSX function is not executed */}
  <div>
    {isAdmin && < span onClick={this.handleEdit}>Edit</ span>}
  </div >

Handling Events:

Always create function on class instance so that new function is not created on each function render

class App extends Component {
  constructor() {
    super();
    this.state = {
      items: []
    };
  }

  handleUpdate(e) {
    // ...
  }

  render() {
    return (
      <div className="App">
        <a onClick={this.handleUpdate}>Add</a>
      </div>
    );
  }
}

Using set state:

You can pass two types of params in setState

Objects

  this.setState({counter : this.state.counter+1 }) 

Most commonly used pattern. Passing objects takes all objects and merges it for all calls.

Function

  this.setState((state) => { counter : this.state.counter+1 })

Passing functions excutes it for every call condition check inside the function

  this.setState((state) => {
    if(state.items.length > 10) return { error: 'limit exceeded' }; 
    return { items : [...] }
  })

Pass in a callback after setstate is complete

  this.setState((state) => {
    return { page : state.page + 1 }
  },callback)