This is the 12th day of my participation in Gwen Challenge

Hi, I’m @Luo Zhu, a blogger who keeps writing. Thank you for every like and comment you make.

This article was first published on luo Zhu’s official website

Translated from Sudheerj/reactJs-interlocution-Questions

This article synchronizes in the public account Luo Zhu early teahouse, reprint please contact the author.

1. How to verify props in React?

When the application is running in development mode, React automatically checks all the props we set up on the component to make sure they have the right type. React generates a warning message on the console if the type is incorrect. It is disabled in production mode due to the performance impact. The required props is defined with isRequired.

Predefined set of props types.

  1. PropTypes.number
  2. PropTypes.string
  3. PropTypes.array
  4. PropTypes.object
  5. PropTypes.func
  6. PropTypes.node
  7. PropTypes.element
  8. PropTypes.bool
  9. PropTypes.symbol
  10. PropTypes.any

We can define propTypes for the User component, as shown below.

import React from 'react';
import PropTypes from 'prop-types';

class User extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired,
  };

  render() {
    return (
      <>
        <h1>{`Welcome, ${this.props.name}`}</h1>
        <h2>{`Age, ${this.props.age}`}</h2>
      </>); }}Copy the code

Note: In React V15.5, PropTypes was moved from React.PropTypes to the prop-types library.

Equivalent functional components:

import React from 'react';
import PropTypes from 'prop-types';

function User() {
  return (
    <>
      <h1>{`Welcome, ${this.props.name}`}</h1>
      <h2>{`Age, ${this.props.age}`}</h2>
    </>
  );
}

User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
};
Copy the code

2. What’s the React advantage?

Here are the main advantages of React.

  1. Improve application performance through the virtual DOM.
  2. JSX makes code easy to read and write.
  3. It can render on both client and server side (SSR).
  4. Easy to integrate with frameworks (Angular, Backbone) because it’s just an image library.
  5. It is easy to write unit and integration tests using tools such as Jest.

3. What are the limitations of React?

In addition to its advantages, React has some limitations.

  1. React is just an image library, not a complete framework.
  2. There is a learning curve for beginners to web development.
  3. Incorporating React into a traditional MVC framework requires some additional configuration.
  4. The complexity of the code increases with the addition of inline templates and JSX.
  5. Too many widgets lead to overengineering or templating.

4. What is Error Boundary in React V16?

An error boundary is a component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a backup UI instead of a crashed component tree.

If a class component defines a new lifecycle method componentDidCatch(Error, info) or static getDerivedStateFromError(), it becomes an error boundary.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // You can also log errors to an error reporting serviceThe info logErrorToMyService (error). }static getDerivedStateFromError(error) {
    // Update the state so that the user interface will be rolled back for the next rendering.
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>{'Something went wrong.'}</h1>;
    }
    return this. Props. Children. }}Copy the code

Then use it as a normal component.

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>
Copy the code

How do React V15 handle error boundaries?

React V15 provides very basic support for error boundaries using the unstable_handleError method. In React V16, it has been renamed componentDidCatch.

6. What is the recommended method of static type checking?

Typically we use the PropTypes library (moved from React V15.5 to the prop-types package) to do type checking in React applications. For large code bases, it is recommended to use a static type checker, such as Flow or TypeScript, that does type checking at compile time and provides auto-completion.

7. react-domWhat’s the use of a bag?

The React-DOM package provides DOM-specific methods that can be used at the top level of your application. Most components do not need this module. Some of the methods for this package are:

  1. render()
  2. hydrate()
  3. unmountComponentAtNode()
  4. findDOMNode()
  5. createPortal()

8. react-domWhat is the purpose of the Render method of

This method is used to render the React element into the DOM in the supplied container and return a reference to the component. If the React element has previously been rendered into the container, it updates it and only changes the DOM to reflect the latest changes if necessary.

ReactDOM.render(element, container[, callback])
Copy the code

If an optional callback is provided, it will be executed after the component has been rendered or updated.

9. What is ReactDOMServer?

The ReactDOMServer object enables you to render components as static tokens (typically for node servers). This object is primarily used for server-side rendering (SSR). The following methods are available for server and browser environments:

  1. renderToString()
  2. renderToStaticMarkup()

For example, you typically run a Node-based Web server (such as Express, Hapi, or Koa), call renderToString to render the root component as a string, and then send it as a response.

/ / use the Express
import { renderToString } from 'react-dom/server';
import MyPage from './MyPage';

app.get('/'.(req, res) = > {
  res.write('
      My Page');
  res.write('<div id="content">');
  res.write(renderToString(<MyPage />));
  res.write('</div></body></html>');
  res.end();
});
Copy the code

10. How do I use innerHTML in React?

The dangerouslySetInnerHTML property is an alternative to the innerHTML used by React in the browser DOM. Just like innerHTML, using this attribute is risky given cross-site scripting (XSS) attacks. You just need to pass an __html object as the key and HTML text as the value.

In this example, MyComponent uses the dangerouslySetInnerHTML attribute to set the HTML tag:

function createMarkup() {
  return { __html: 'First &middot; Second' };
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}
Copy the code