-
How to apply validation on props in React?
When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact. The mandatory props are defined with
isRequired.The set of predefined prop types:
PropTypes.numberPropTypes.stringPropTypes.arrayPropTypes.objectPropTypes.funcPropTypes.nodePropTypes.elementPropTypes.boolPropTypes.symbolPropTypes.any
We can define
propTypesforUsercomponent as 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> </> ) } }Note: In React v15.5 PropTypes were moved from
React.PropTypestoprop-typeslibrary.The Equivalent Functional Component
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 } -
What are the advantages of React?
Below are the list of main advantages of React,
-
Increases the application's performance with Virtual DOM.
-
JSX makes code easy to read and write.
-
It renders both on client and server side (SSR).
-
Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
-
Easy to write unit and integration tests with tools such as Jest.
-
-
What are the limitations of React?
Apart from the advantages, there are few limitations of React too,
-
React is just a view library, not a full framework.
-
There is a learning curve for beginners who are new to web development.
-
Integrating React into a traditional MVC framework requires some additional configuration.
-
The code complexity increases with inline templating and JSX.
-
Too many smaller components leading to over engineering or boilerplate.
-
-
What are error boundaries in React v16?
Error boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
A class component becomes an error boundary if it defines a new lifecycle method called
componentDidCatch(error, info)orstatic getDerivedStateFromError():class ErrorBoundary extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } componentDidCatch(error, info) { // You can also log the error to an error reporting service logErrorToMyService(error, info) } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. 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 } }After that use it as a regular component:
<ErrorBoundary> <MyWidget /> </ErrorBoundary> -
How error boundaries handled in React v15?
React v15 provided very basic support for error boundaries using
unstable_handleErrormethod. It has been renamed tocomponentDidCatchin React v16. -
What are the recommended ways for static type checking?
Normally we use PropTypes library (
React.PropTypesmoved to aprop-typespackage since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features. -
What is the use of
react-dompackage?The
react-dompackage provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:-
render() -
hydrate() -
unmountComponentAtNode() -
findDOMNode() -
createPortal()
-
-
What is the purpose of render method of
react-dom?This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.
ReactDOM.render(element, container[, callback])If the optional callback is provided, it will be executed after the component is rendered or updated.
-
What is ReactDOMServer?
The
ReactDOMServerobject enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:renderToString()renderToStaticMarkup()
For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call
renderToStringto render your root component to a string, which you then send as response.// using Express import { renderToString } from 'react-dom/server' import MyPage from './MyPage' app.get('/', (req, res) => { res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>') res.write('<div id="content">') res.write(renderToString(<MyPage/>)) res.write('</div></body></html>') res.end() }) -
How to use innerHTML in React?
The
dangerouslySetInnerHTMLattribute is React's replacement for usinginnerHTMLin the browser DOM. Just likeinnerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a__htmlobject as key and HTML text as value.In this example MyComponent uses
dangerouslySetInnerHTMLattribute for setting HTML markup:function createMarkup() { return { __html: 'First · Second' } } function MyComponent() { return <div dangerouslySetInnerHTML={createMarkup()} /> }