[20] Front-end internship: react official document learning (Advanced Guide: React refs and pop-up windows / MyErrorBoundary /suspense / Context)

Posted by massimoGornatti on Wed, 28 Aug 2019 12:42:31 +0200

React refs and pop-up windows

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


class OuterClickExample extends React.Component {
  constructor(props) {
    super(props);

    this.state = { isOpen: false };
    this.toggleContainer = React.createRef();

    this.onClickHandler = this.onClickHandler.bind(this);
    this.onClickOutsideHandler = this.onClickOutsideHandler.bind(this);
  }

  componentDidMount() {
    window.addEventListener('click', this.onClickOutsideHandler);
  }

  componentWillUnmount() {
    window.removeEventListener('click', this.onClickOutsideHandler);
  }

  onClickHandler() {
    this.setState(currentState => ({
      isOpen: !currentState.isOpen
    }));
  }

  // Click on the blank to close the window
  onClickOutsideHandler(event) {
    if (this.state.isOpen && !this.toggleContainer.current.contains(event.target)) {
      this.setState({ isOpen: false });
    }
  }

  render() {
    return (
      <div ref={this.toggleContainer}>
        <button onClick={this.onClickHandler}>Select an option</button>
        {this.state.isOpen && (
          <ul>
            <li>Option 1</li>
            <li>Option 2</li>
            <li>Option 3</li>
          </ul>
        )}
      </div>
    );
  }
}

ReactDOM.render(
  <OuterClickExample/>,
  document.getElementById('root')
);

serviceWorker.unregister();

**************** can also be implemented with onBlur and onFocus ********************

onBlur and onFocus are commonly used to implement form functions. The former is triggered when an element loses focus, and the latter is triggered when an element gains focus.

class BlurExample extends React.Component {
  constructor(props) {
    super(props);

    this.state = { isOpen: false };
    this.timeOutId = null;

    this.onClickHandler = this.onClickHandler.bind(this);
    this.onBlurHandler = this.onBlurHandler.bind(this);
    this.onFocusHandler = this.onFocusHandler.bind(this);
  }

  onClickHandler() {
    this.setState(currentState => ({
      isOpen: !currentState.isOpen
    }));
  }

  // We close the popover on the next tick by using setTimeout.
  // This is necessary because we need to first check if
  // another child of the element has received focus as
  // the blur event fires prior to the new focus event.
  onBlurHandler() {
    this.timeOutId = setTimeout(() => {
      this.setState({
        isOpen: false
      });
    });
  }

  // If a child receives focus, do not close the popover.
  onFocusHandler() {
    clearTimeout(this.timeOutId);
  }

  render() {
    // React assists us by bubbling the blur and
    // focus events to the parent.
    return (
      <div onBlur={this.onBlurHandler}
           onFocus={this.onFocusHandler}>

        <button onClick={this.onClickHandler}
                aria-haspopup="true"
                aria-expanded={this.state.isOpen}>
          Select an option
        </button>
        {this.state.isOpen && (
          <ul>
            <li>Option 1</li>
            <li>Option 2</li>
            <li>Option 3</li>
          </ul>
        )}
      </div>
    );
  }
}

 

[2] React.lazy and import

 

React.lazy

Be careful:

React.lazy and Suspense are not yet available for server-side rendering. If you want to decompose code in server-rendered applications, we recommend using Loadeable components . It has a very good one. Guide for bundling server-side rendering.

This React.lazy function allows you to render dynamic imports as regular components.

 

[3]suspense

 

[4] MyErrorBoundary is used to deal with network reasons, resulting in component content being unable to load.

[5] Routing-based code splitting

 

[6] Named export

 

[7]context

Context provides a way to pass data through a component tree without having to pass props manually at each level.

In a typical React application, data is passed from top to bottom (parent object) through props, but this can be cumbersome for some types of props required by many components of the application, such as locale preferences, UI themes. Context provides a way to share these values between components without explicitly passing prop through each level of the tree.

//Context allows us to drill a value into the component tree / without explicitly traversing each component. / Create a context for the current topic (default is "light").
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Use the provider to pass the current topic to the tree below. / Any component can read it, no matter how deep it is. // In this example, we use "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

//Intermediate components no longer need to explicitly pass topics.
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  //Assign ContextType to read the current topic context. // Reaction will find the closest theme provider above and use its value. // In this case, the current theme is "Dark".
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

Example: Topic Background Change

Referring to official documents: https://reactjs.org/docs/context.html#when-to-use-context

 

[8] Handling errors

If its lifecycle approach limits any (or both) class component to an error boundary static getDerivedStateFromError() or componentDidCatch() . Used for static getDerivedStateFromError() to render a fallback UI after an error is thrown. Use componentDidCatch() to record error messages.

 

 

Topics: React Windows network