in the daily development of the team, people write components of different quality and styles, and there are many ways of naming them. For example, some use tags as component names, but I won't say who they are. Components cannot be extended or difficult to maintain because of many requirements. It is quite difficult to reuse the functions of many business components. so in today's article we'll talk about how to set up an elegant React component in terms of component design patterns. basic principles of component design when designing a high-quality component or a set of high-quality components, we should first follow the following principles, including the following aspects. single responsibility the principle of single responsibility is to make a module focus on a Phoenix girl, that is, to minimize the responsibility of a module. If a module has too many functions, it should be divided into multiple modules, which is more conducive to the maintenance of the code. A single component is easier to maintain and test, but don't abuse it, split components if necessary, minimize granularity at one extreme, and may result in a large number of modules, and module discretization can make the project difficult to manage. demarcate boundaries how to split components, if the two components are too closely related to logically clearly define their respective responsibilities, then the two components should not be split. Otherwise, if their respective responsibilities are not clear and the boundaries are not distinct, the problem of logical confusion will arise. Then the most important thing to split the components…

May 8, 2023 0comments 1270hotness 0likes Aaron Read all

let's start with some nonsense I remember this hooks very well, because at that time, during an interview, I was asked to implement this custom hooks by hand, , so it was prepared for the first hooks in this series. to see the effect when our component becomes complex, do you want to know what caused the component to render, or what the value change is, this hooks will solve your problem. here comes the hooks source code type IProps = Record<string, unknown>; / * * * what caused the page render to customize hooks * *@paramName of the componentName observation component *@paramData that props needs to observe (data such as current component state or incoming props that may cause rerender) , / const useWhyDidYouUpdate = (componentName: any, props: any) => { // create a ref object let oldPropsRef = useRef<IProps>({}); useEffect(() => { if (oldPropsRef.current) { // iterate through all the key of the old and new props let keys = Object.keys({ ...oldPropsRef.current, ...props }); // change the information object let changeMessageObj: IProps = {}; keys.forEach((key) => { // compare whether the new and old props are changed, changed and recorded to changeMessageObj if (!Object.is(oldPropsRef.current[key], props[key])) { changeMessageObj[key] = { from: oldPropsRef?.current[key], to: props[key], }; } }); // whether there is change information, existence and printing if (Object.keys(changeMessageObj).length) { console.log(componentName, changeMessageObj); } // Update ref oldPropsRef.current = props; } }); }; demo complete source code import React, { useState, useRef, useEffect } from 'react'; import { Button, Statistic } from 'antd'; type IProps = Record<string, unknown>; / * *…

May 8, 2023 0comments 1361hotness 0likes Aaron Read all

Array generate array when you need to generate an array of 0-99 scenario 1 const createArr = (n) => Array.from(new Array(n), (v, i) => i) const arr = createArr(100) // 0-99 array scenario 2 const createArr = (n) => new Array(n).fill(0).map((v, i) => i) createArr(100) // 0-99 array disrupt the array when you have an array, you need to disrupt the sorting of the array const randomSort = list => list.sort(() => Math.random() - 0.5) randomSort([0,1,2,3,4,5,6,7,8,9]) // randomly arrange the results Array deduplication when you need to keep only one for all the repeating elements in the array const removeDuplicates = list => [...new Set(list)] removeDuplicates([0, 0, 2, 4, 5]) // [0,2,4,5] most groups take intersection when you need to take the intersection of multiple arrays const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v))) intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9]) // [3, 4] find maximum index but you need to find an index of the largest value in the array const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0); indexOfMax([1, 3, 9, 7, 5]); // 2 find the minimum index when you need to find the index of the lowest value in an array const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0) indexOfMin([2, 5, 3, 4, 1, 0, 9]) // 5 find the nearest value when you need to find the closest value in an array const closest = (arr,…

May 7, 2023 0comments 1349hotness 0likes Aaron Read all

React Router is a routing library for React applications that provides an easy way to match URL to components. React Router implements the following main concepts: Router: it provides the basic routing capabilities of the application. Routes: it defines the mapping between URL and components. Link: it provides a convenient way to navigate through the application. Switch: it is used to ensure that only one route can match the current URL. createBrowserHistory: this is used to create an instance of HTML5 History API. next, we will delve into the implementation principle of React Router. We will first discuss the implementation of Router components, then discuss the implementation of Routes components, and finally discuss the implementation of Link components. implementation of Router components The Router component is the core component of the React Router library, which provides the basic routing capabilities of the application. The following is the simplified version of the Router component implementation code: const Router = ({ children }) => { const [location, setLocation] = useState(window.location.pathname); useEffect(() => { const handlePopState = () => setLocation(window.location.pathname); window.addEventListener('popstate', handlePopState); return () => window.removeEventListener('popstate', handlePopState); }, []); return <RouterContext.Provider value={{ location }}>{children}</RouterContext.Provider>; }; in the above code, we first define a Router component. It accepts a children attribute, which is the root component of our application. Then we use useState Hook to create a state variable named location . It will be used to track the current URL. We will update this state variable using the setLocation function. next, we use useEffect Hook to register a function that listens for popstate…

May 6, 2023 0comments 1344hotness 0likes Aaron Read all

During the development of a project, designers will inevitably create animated effects to enhance the user experience. If the current effect does not require interaction and is only for display, we can use GIF or APNG to achieve the effect. but if the current animation requires other interactions in addition to presentation, or even a component requires animation effects, it would be unreasonable to use a picture format. So I wrote an extremely simple css animation library rc-css-animate . Here we directly use animate.css as the dependent library for css animation. Animate.css not only provides many interactive animation style classes, but also provides animation running speed, latency, and the number of repetitions and other style classes. as you can see, the default animate.css build animation needs to carry the prefix "animate__". <h1 class="animate__animated animate__bounce">An animated element</h1> of course, the library encapsulates css animation and still supports other animation libraries as well as their own handwritten css animation, but this library is not recommended if developers need to control all kinds of complex animation. use can be used in the following ways: import React, { useRef } from "react"; import ReactCssAnimate from "rc-css-animate"; // introduce animate.css as an animation dependency import "animate.css"; function App() { const animateRef = useRef(null); return ( <div className="App"> <ReactCssAnimate // Define the components that currently display the animation // Use by default div tag="div" // Of the current component className className="" // Of the current component style style={{}} // Of the current component ref ref={animateRef} // Animation prefix clsPrefix="animate__" // Of the current animation className animateCls="animated…

May 6, 2023 0comments 1431hotness 0likes Aaron Read all

when a React application logic becomes complex, the time taken by the component render increases significantly. If it takes too long to render from the component render to the view, the user will feel the page stutter. there are two ways to solve this problem: change the process of the component render from synchronous to asynchronous, so that the render process page does not get stuck. This is the principle of concurrent updates reduce the number of components requiring render , which is often referred to as React performance optimization usually, we take the above different approach for different types of components. For example, for input boxes with time-consuming logic such as the following, method 1 is more appropriate (because concurrent updates reduce stutters at input): function ExpensiveInput({onChange, value}) { // time-consuming operation const cur = performance.now(); while (performance.now() - cur < 20) {} return <input onChange={onChange} value={value}/>; } so, can you take into account both of these two ways at the whole application level? The answer is-- not really. this is because, for complex applications, concurrent updates are often contrary to performance optimization. That's what this article is about-the concurrency paradox. start with performance optimization for a component, if you want it not to be render , the basic condition that needs to be achieved is that the reference of props remains unchanged. for example, in the following code, Child components depend on fn props . Because fn is inline, references change every time App > component render , which is not conducive to Child performance optimization: function App()…

May 5, 2023 0comments 1266hotness 0likes Aaron Read all

Hello, everyone. I'm Carson. The code volume of React can be said to be quite large. Is there a function in such a large library that is not mentioned in the document but actually exists ? the answer is yes. this article will introduce you to hidden egg features that are not mentioned in three documents. ref cleanup in the current React , Ref has two data structures: <T>(instance: T) => void {current: T} for most requirements, we will use the second data structure. It is also the data structure returned by useRef and createRef . the first data structure is mainly used for DOM monitoring. For example, in the following example, the size of div is reflected in the height state: function MeasureExample() { const [height, setHeight] = useState(0); const measuredRef = useCallback(node => { if (node !== null) { setHeight(node.getBoundingClientRect().height); } }, []); return ( <div ref={measuredRef}>Hello Kasong</div> ); } but in the above example, the size change of DOM cannot be reflected in real time to the height state. To reflect real-time changes, you need to use native API that monitors DOM , such as ResizeObserver , monitor DOM size change IntersectionObserver , monitor DOM visual area changes MutationObserver , monitor DOM tree changes these API are usually event-driven, which involves unbinding events when monitoring is not needed. since event binding occurs in the ref callback, naturally, unbinding events should also occur in the ref callback. For example, modify the above example with ResizeObserver : function MeasureExample() { const [entry, setEntry] = useState(); const measuredRef = useCallback((node)…

May 5, 2023 0comments 1344hotness 0likes Aaron Read all

recently I saw some useful React tool libraries, summed up and shared them with you to avoid duplicating wheels. I hope it will be helpful to you ~ I. basic 1. React Infinite Scroller React Infinite Scroller is used to load content indefinitely in a React project. npm address: www.npmjs.com/package/rea... 2. react-dnd React DnD is a set of React high-level components created by React and Dan Abramov, the core author of Redux, that can help build complex drag-and-drop interfaces while keeping components separate. It is mainly used for drag and drop of components. npm address: www.npmjs.com/package/rea... 3. react-beautiful-dnd react-beautiful-dnd is a beautiful and easy-to-use React list drag-and-drop library. ​ npm address: www.npmjs.com/package/rea... 4. react-icons using react-icons, you can easily include popular icons in React projects. ​ npm address: www.npmjs.com/package/rea... 5. react-share react-share is a React social media sharing button and sharing library. ​ npm address: www.npmjs.com/package/rea... 6. create-react-app Create React App is a command line interface tool that allows you to quickly create and run React applications without any configuration. ​ npm address: www.npmjs.com/package/cre... 7. react-intl React Intl provides a React component and Mixin for internationalizing React Web applications. It provides a description of formatted date, number, and string messages. ​ npm address: www.npmjs.com/package/rea... 8. react-router react-router is a routing solution routing solution for React.js. It can easily synchronize your app and URL while providing first-class support for nesting, transformation, and server rendering. ​ npm address: www.npmjs.com/package/rea... 9. React Virtualized react-virtualized is a responsive component that renders large list and table data efficiently and can be used to solve long…

May 4, 2023 0comments 1549hotness 0likes Aaron Read all

Preface Dropdown drop-down menu import import Dropdown from '@/components/Dropdown/Dropdown' The use of subcomponents is as follows: const MenuItem = Dropdown.MenuItem; const SubMenu = Dropdown.SubMenu; Props 1. trigger Type: string (required) default: click | hover description: drop-down trigger mode, click click trigger menu, hover trigger menu 2. onClickMenu Type: func default value: no description: click to trigger the callback function to change the classname of the sub-component. Input parameters: {string} trigger drop-down trigger mode 3. title Type: string default value: no description: drop-down button prompts for title MenuItem child content components import import Dropdown from '@/components/Dropdown/Dropdown'; Props 1. trigger Type: string (required) default: click | hover description: drop-down trigger mode, click click trigger menu, hover trigger menu 2. className Type: string (required) default: click | hover description: class:'dropdownType-click' of the outer div of the sub-content | 'dropdownType-hover' 3. disabled Type: bool default value: false Note: the sub-content of the drop-down is grayed out, true is grayed out, false is normal 4. onClickMenuItem Type: func (required) default value: no description: click on a single sub-content to perform the action. Input parameters: {string | number} value | some item selected by key parent of SubMenu child content import import Dropdown from '@/components/Dropdown/Dropdown'; Props 1. trigger Type: string (required) default: click | hover description: drop-down trigger mode, click click trigger menu, hover trigger menu 2. className Type: string (required) default: click | hover description: class:'dropdownType-click' of the outer div of the sub-content | 'dropdownType-hover' 4. title Type: string default value: no description: drop-down button prompts for title Let's implement dropdown.js import React from 'react';…

May 4, 2023 0comments 1592hotness 0likes Aaron Read all

controlled and uncontrolled components React the concept of controlled and uncontrolled components is relative to the form. In React , the form element usually holds the internal state , so it works differently from other HTML elements. The different implementation of state within the form element results in controlled and uncontrolled components. controlled components in the HTML form elements, they usually maintain a set of state and update UI as the user inputs. This behavior is not controlled by our program. If we establish a dependency between the state attribute and the value of the form element in React , then update the state attribute through the onChange event and setState () . You can control what happens to the form during user input. React form input elements that control values in this way are called controlled components. & nbsp; if a input input box is defined in React , it does not have the same bi-directional binding function as v-model in Vue , that is to say, we do not have an instruction to combine the data with the input box, and the user enters the content in the input box, and then the data is updated synchronously. class Input extends React.Component {   render () {     return <input name="username" />   } } when users enter content in the input box on the interface, it maintains a state . This state is not the this.state that we usually see, but the abstract state on each form element, so that we can update the UI according to…

May 3, 2023 0comments 1299hotness 0likes Aaron Read all
167891012