bredom
4/13/2019 - 1:12 AM

React Useful Information

//Changing state
this.setState({comment: 'Hello'});

//Reading current state and props when changing state
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

//Binding "this" to point to the component can be done with "bind" or with arrow function
//Without this using a class method in event handler like onClick will cause problem because "this" won't point on the Component but on a button
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isToggleOn: true
    };
    //Binding using "bind"
    //this.handleClick = this.handleClick.bind(this);
  }
  //Binding using arrow function in the class
  handleClick = () => {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    )
  }
  
  //Binding using arrow function in render method
  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

//Passing arguments to events
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>


//Ejecting React to use CSS modules
1. npm run eject
2. Open config->webpack.config.js
3. Add two lines to css loader section
{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
    importLoaders: 1,
    modules: true, //modules
    localIdentName: '[name]__[local]__[hash:base64:5]', //indentation
    sourceMap: isEnvProduction && shouldUseSourceMap,
  }),
  // Don't consider CSS imports dead code even if the
  // containing package claims to have no side effects.
  // Remove this when webpack adds a warning or an error for this.
  // See https://github.com/webpack/webpack/issues/6571
  sideEffects: true,
},