951 Matching Annotations
  1. Apr 2020
    1. It’s still a good idea to keep your code in three different buckets, and keep these buckets isolated from each other:Display/UI ComponentsProgram logic/business rules — the stuff that deals with the problem you’re solving for the user.Side effects (I/O, network, disk, etc.)

      How do I organize my code like this? What's the directory structure look like.

    1. 。如果同一个文件夹下有同名而不同作用的js文件,则通过中缀(小写)进一步区分

      考虑使用中缀

    1. When a React component dispatches actions, how can another service catch the actions, accumulate and group them, then redispatch a single action?

      Catching actions to accumulate and group them

    1. JSX 的属性都采用双引号

      这规则跟Taro冲突

    2. 扩展名:React 组件使用.jsx扩展名;文件名:文件名使用帕斯卡命名。 例如: ReservationCard.jsx。引用命名:React 组件使用帕斯卡命名,引用实例采用驼峰命名

      React组件命名以大写字母开头。

  2. Mar 2020
    1. Inputs are collected in standard React fashion with some hooks:

      To be honest, I'm not the most well-versed in best practices surrounding the new React hooks, so I could be wrong here / doing things in a convoluted way. The code here is a carry-over from the template I mention

      (this comment is also a test of hypothes.is annotations on my blog!)

    1. To do that, the react-redux library comes with 2 things: a component called Provider, and a function called connect.

      react-redux带来两样东西: 一个叫Provider的组件 一个叫connect的函数

    1. useEffect serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API

      useEffect将几个功能给统一在一起了。

    1. Newer versions of TypeScript can now infer types based on your React.PropTypes (PropTypes.InferProps), but the resulting types can be difficult to use or refer to elsewhere in your code.

      新版TS能通过PropTypes推断类型,但是结果类型不大好用。

    1. Every useState() call gets its own “memory cell”.

      Hooks proposal relies on call order, isolating multiple name state variables from each other.

    2. point of supporting multiple useState() calls is so that you can extract parts of stateful logic (state + effects) out of your components into custom Hooks which can also independently use local state and effects

      Reasons to avoid managing state via a single object instead of discrete state variables

    3. array destructuring syntax to name useState() state variables but these names are not passed to React. Instead, in this example React treats name as “the first state variable”, surname as “the second state variable”, and so on. Their call index is what gives them a stable identity between re-renders

      Stable identity of useState variables between re-renders

    1. The combination of WordPress, React, Gatsby and GraphQL is just that - fun

      Intriguing combination of technologies.

      Keep an eye on the post author, who is going to discuss the technologies in the next writings

  3. Feb 2020
  4. Jan 2020
    1. const mapStateToProps = state => ({ todos: getVisibleTodos(state.todos, state.visibilityFilter)})const mapDispatchToProps = dispatch => ({ toggleTodo: id => dispatch(toggleTodo(id))})export default connect( mapStateToProps, mapDispatchToProps)(TodoList)

      Example of passing state to the component.

    1. npx create-react-app my-app

      This builds out a nice template project to get started with all the tooling and setup already done for you.

    1. Instead of allowing any and all components to fetch and manipulate data, which can make debugging pretty much suck, we want to implement a pattern that's in line with the Single Responsibility Principle, and that keeps our code DRY.
  5. Dec 2019
    1. Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI.

      key point!

    2. What does useEffect do? By using this Hook, you tell React that your component needs to do something after render

      key point!

    3. In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM.

      key point!

    4. Custom Hooks are more of a convention than a feature. If a function’s name starts with ”use” and it calls other Hooks, we say it is a custom Hook. The useSomething naming convention is how our linter plugin is able to find bugs in the code using Hooks.

      as can be seen above, indeed nothing explicetly tells that the function is a special kind of hook. its just a function...

    1. Places To Hire Top React Developers In 2020

      It becomes even more crucial to select great people when you are hiring for a new business. Hiring top react developers has become even more difficult in the last few years because of its growing popularity and usability amongst companies of all sizes.

    1. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects

      key point. this means that all those small messing of variables in code that gets rendered into the template of the component? this is all 'side effects', and of course we do this all the time...

    1. If you need more advanced React-integration, like server rendering, redux, or react-router, see shakacode/react_on_rails, react-rails, and webpacker-react.
    1. server-side rendering is strict about configuration, and the best way to find out what's wrong is to compare your project to an already working setup. Check out the reference implementations, bit by bit.
    1. I love this library. Migrated from CRA to nwb. That didn't work out. Neutrino was very easy to setup with almost the exact setup I had with CRA but with far more customization. Again, thank you. Have a good day
    1. Second, there are some fantastic projects out there like Create React App, preact-cli, nwb, and much more that avoid the boilerplate problem but at the expense of some other tradeoffs. Your configuration could be black-boxed and not able to be modified. They could force you to eject your configuration, making maintenance of the entire build dependency tree and configuration your responsibility again, and also preclude future configuration updates.
    1. make stylable all of the visual states of your application - no clicking around required - just jump right to the state

      Storybook value proposition: state inventory without requiring interactions

    2. The easy, functional-programming concept that a component can receive both functions AND data as arguments

      Injecting a function, a fp concept, to enable testing

    3. in React, the component doesn't encapsulate completely around the lookup method. It provides a default implementation but allows its environment to override it

      React functional component receives method to enable testing

  6. Nov 2019
    1. const setRefs = useRef(new Map()).current; const { children } = props; return ( <div> {React.Children.map(children, child => { return React.cloneElement(child, { // v not innerRef ref: node => { console.log('imHere'); return !node ? setRefs.delete(child.key) : setRefs.set(child.key, node)

      Illustrates the importance of having unique keys when iterating over children, since that allows them to be used as unique keys in a Map.

    1. Wow, looks like a lot of duplication in https://github.com/constelation/monorepo/blob/master/packages/Style_/src/index.native.tsx compared to https://github.com/constelation/monorepo/blob/master/packages/Style_/src/index.tsx to handle differences in props on the different platforms such as backfaceVisibility.

      And even structure/shape differences like:

      const style = { ...styleFromProps, ...this.props.style, ...Child.props.style }
      

      vs.

          propsToPass.style = [styleFromProps, this.props.style, Child.props.style]
      

      Is there no way to remove this duplication?

    1. // require('hammerjs') when in a browser. This is safe because Hammer is only // invoked in componentDidMount, which is not executed on the server. var Hammer = (typeof window !== 'undefined') ? require('hammerjs') : undefined
    1. In fact, React itself now makes use of render props in its own context API
    2. For example, if you were to add a className prop to the top or bottom <div> in the above demo, the <List> component would remove it in place of the top or bottom class. You can see this in the following example, where I’ve added the highlight class to the top two rows, but only the middle row is actually highlighted.To fix this, you’ll need to append a string to the className instead of replacing it.
    3. here’s how you’d use React.Children.toArray() with React.cloneElement() to add top and bottom classes to the List component’s children.
    1. It is used to expose internal data from within a render prop component for making it accessible to other components within the render prop component's composition.
    2. However, in this case you would lose the possibility to render something in between. You are strictly coupled to the higher-order component's render method. If you need to add something in between of the currency components, you would have to do it in the higher-order component. It would be quite similar as you have done it previously by rendering the currency components straight away in the Amount component. If using a render prop component instead, you would be flexible in your composition.
    3. For the sake of completeness, the following code demonstrates that the problem could be solved with a higher-order component (HOC) as well:
    4. That's especially useful when combining it with React's slot pattern, which is used for passing multiple composed components to different places within a (render prop) component, but then advancing it with a render prop function to pass the state from the render prop component to the composed components.
    5. However, again you would have to lift state up to the App component in order to pass the amount to the currency components. As you can see, the component composition on its own doesn't help us to solve the problem. That's the point where React's render props pattern comes into play which enhances React's component composition with an important ingredient: a render function.
    6. But it's not that simple, because the currency components don't know about the amount now. You would have to lift the state from the Amount component to the App component.
    1. Component Registration components A map of component names to plain JavaScript components. frameworkComponents A map of component names to framework (React, Angular etc) components.
    1. When the grid is initialised, it will fire the gridReady event. If you want to use the API of the grid, you should put an onGridReady(params) callback onto the grid and grab the api from the params. You can then call this api at a later stage to interact with the grid (on top of the interaction that can be done by setting and changing the props).
    1. whenever there's a lot going on, computers (but mostly humans) will get stuff wrong. In the 6 lines of our component, rendering 2 node types, we change syntaxes from JS to JSX, and back, 8 times! Count them - it's like JS(JSX(JS(JSX(JS))))! This is not the simplest code we can write.

      render() {

        { languages.map(item => (
      • {item}
      • )) }
      }

    1. Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

      key point, for security reasons

    2. To share variables between Sass files, you can use Sass imports. For example, src/App.scss and other component style files could include @import "./shared.scss"; with variable definitions

      just like we do in other project, say an Angular app. So the React components will use composition but in the sass files, we can use import() and @extends

    1. To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

      key point that summarizes it all

    2. Conceptually, React does work in two phases: The render phase determines what changes need to be made to e.g. the DOM. During this phase, React calls render and then compares the result to the previous render. The commit phase is when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like componentDidMount and componentDidUpdate during this phase. The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming async mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption). Render phase lifecycles include the following class component methods: constructor componentWillMount componentWillReceiveProps componentWillUpdate getDerivedStateFromProps shouldComponentUpdate render setState updater functions (the first argument) Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be non-deterministic. Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods: Class component constructor method The render method setState updater functions (the first argument) The static getDerivedStateFromProps lifecycle

      key point! This isn't just relevant for StrictMode but also gives some high level summary of React

    3. When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls componentWillReceiveProps() and componentWillUpdate() on the underlying instance.

      this is a key point: that's why on React apps you'll see UI updated but notice there was no real teardown and re instantiation of the component. Also, this is how state is kept but the UI is updated

    4. One caveat is that some “falsy” values, such as the 0 number, are still rendered by React. For example, this code will not behave as you might expect because 0 will be printed when props.messages is an empty array: <div> {props.messages.length && <MessageList messages={props.messages} /> } </div> To fix this, make sure that the expression before && is always boolean: <div> {props.messages.length > 0 && <MessageList messages={props.messages} /> } </div>

      This is important for bug prevention and fixing!

    5. When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent:

      which probably means that is better to use literals as we get escaping for free and that's a good practice.

    6. User-Defined Components Must Be Capitalized When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file. We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

      this is the 'why' explanation on why a capital letter is required with user-defined components. In other words - passed as string or as the type to React.createElement():

      React.createElement(MyComp) vs React.createElement('div')

    7. The most common signature for HOCs looks like this: // React Redux's `connect` const ConnectedComment = connect(commentSelector, commentActions)(CommentList); What?! If you break it apart, it’s easier to see what’s going on. // connect is a function that returns another function const enhance = connect(commentListSelector, commentListActions); // The returned function is a HOC, which returns a component that is connected // to the Redux store const ConnectedComment = enhance(CommentList); In other words, connect is a higher-order function that returns a higher-order component!

      probably a common and useful example that is used with Redux

    8. return class extends React.Component {

      Cool! anonymous/unnamed classes used here

    9. A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. Concretely, a higher-order component is a function that takes a component and returns a new component.

      Key point. The compositional nature of React guides us in this pattern's direction

    10. In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.
    11. Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components.

      A good example for when to use uncontrolled components

    12. However, sometimes the same data needs to be accessible by many components in the tree, and at different nesting levels. Context lets you “broadcast” such data, and changes to it, to all components below

      key point - this is the differentiator consideration to choose context or "passing down" a ready made component from upper level component

    13. The same functionality can be achieved by using appropriate event handlers instead, such as onBlur and onFocus:

      cool! also read above to understand more. basically, this means that "blurring focus" on an element will programatically close some other element

    14. To build a static version of your app that renders your data model, you’ll want to build components that reuse other components and pass data using props. props are a way of passing data from parent to child. If you’re familiar with the concept of state, don’t use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don’t need it.

      key point: state is used when data changes over time. If there's no such need, don't introduce state - keep it simple

    15. Anything inside the <FancyBorder> JSX tag gets passed into the FancyBorder component as a children prop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.

      key point - the 'magic' of 'children'

    16. into the changes in the Calculator, let’s recap our changes to the TemperatureInput component. We have removed the local state from it, and instead of reading this.state.temperature, we now read this.props.temperature.

      effectively injecting change handler by the parent, that will take care of state syncing between all participating parties

    17. Keys only make sense in the context of the surrounding array.

      see example below...

    18. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.

      key point: using setState() "notes" React of a... state change and it triggers change detection and re-rendering of the component.

    1. The language for writing React. Reason's creator also created ReactJS, whose first prototypes were written in SML, a distant cousin of OCaml. We've transcribed ReactML into ReactJS for wide adoption. A few years later, we're now iterating on the future of ReactJS through ReasonReact.
    1. We might have some dirty mutable objects for performance - but our high-level API should be purely functional. You should be able to follow the React model of modelling your UI as a pure function of application state -> UI.
    1. Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children). So, anything you can do with JSX can also be done with just plain JavaScript.

      key point (repeated elsewhere in React documentation, but important nevertheless).

    1. .

      The example below is a very nice basic 'modal' example. Many libraries use such 'portal' implementations

    1. It makes sense that the incoherent render would not be committed to browser and that it would not have any consequences most of the time. But that means that you render logic must be ready to manage incoherency between props and states without crashing. E.g. a list of resource ids in props that doesn't match a list of http requests from a previous id list in the state could lead to weird situations. This is a worry that didn't exist in class components.
    2. But that means that you render logic must be ready to manage incoherency between props and states without crashing
    3. Notice that when you increment the row, ScrollView renders twice but ScrollingDown only renders once receiving only the last version of ScrollView's state.
    1. React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
    2. you can update the state right during rendering. React will re-run the component with updated state immediately after exiting the first render so it wouldn’t be expensive
    1. Each time the ID changes, the EmailInput will be recreated and its state will be reset to the latest defaultEmail value. (Click here to see a demo of this pattern.) With this approach, you don’t have to add key to every input. It might make more sense to put a key on the whole form instead. Every time the key changes, all components within the form will be recreated with a freshly initialized state. In most cases, this is the best way to handle state that needs to be reset.
    2. The terms “controlled” and “uncontrolled” usually refer to form inputs, but they can also describe where any component’s data lives. Data passed in as props can be thought of as controlled (because the parent component controls that data). Data that exists only in internal state can be thought of as uncontrolled (because the parent can’t directly change it).
    1. So the main thing this gives us is a way to set indeterminate property of input via an indeterminate property?

      This is misnamed. Doesn't actually give us a tri-state checkbox. Just a binary checkbox.

    1. input.indeterminate = indeterminate

      So the main thing this gives us is a way to set indeterminate property of input via an indeterminate property?

      Not sure how that supposedly gives us a tri-state checkbox.

    1. Since the checkbox is rendering an input I would work with it rather than focusing on the image. You could do something like this: const checkbox = getByTestId('checkbox-1234').querySelector('input[type="checkbox"]') expect(checkbox).toHaveProperty('checked', true)
    2. the way Material UI works is it renders a different SVG when the checkbox is clicked, and not changing the attributes or anything on the actual input element. So how do I actually test that the element is checked in line with the react-testing-library philosophy?

      These tags belong to entire page. This quote is just supporting evidence for the tags.

    1. this shows that it’s easy to achieve with React even without React directly supporting it.
    2. It seems like we’re not doing it because it’s impossible to support with server rendering, and we’re currently only supporting a subset of attributes/properties that are compatible both with client and server rendering.
    1. This section introduces how React components using the ag-Grid Data Table can take advantage of a Redux store to simplify state management.
    1. Mentioned at https://kentcdodds.com/blog/tools-without-config:

      There is a project called react-app-rewired by Tim Arney. It's awesome. However, I've taken a different approach to making paypal-scripts configurable. ...

    1. Tests implementation details a bit (child component props received), but pretty good other than that.

      https://www.robinwieruch.de/react-testing-tutorial, for example, says that is reasonable to do:

      an integration test could verify that all necessary props are passed through from the tested component to a specific child component.

    1. Here are my tools of choice for testing React apps:react-test-renderer for snapshot unit testingAct API for unit testing React componentsJest for unit and integration testing of JavaScript codeCypress for end to end / ui testing
    1. I don't recommend unit testing stateful components, or components with side-effects. Write functional tests for those, instead, because you'll need tests which describe the complete end-to-end flow, from user input, to back-end-services, and back to the UI. Those tests frequently duplicate any testing effort you would spend unit-testing stateful UI behaviors. You'd need to do a lot of mocking to properly unit test those kinds of components anyway, and that mocking may cover up problems with too much coupling in your component.
    1. Snapshot Test: Introduced by Facebook’s library Jest, Snapshot Tests should be the lightweight variation of testing (React) components. It should be possible to create a DOM snapshot of a component once a test for it runs for the first time and compare this snapshot to a future snapshot, when the test runs again, to make sure that nothing has changed. If something has changed, the developer has to either accept the new snapshot test (the developer is okay with the changes) or deny them and fix the component instead.
  7. Oct 2019
    1. MDX is a superset of Markdown. It allows you to write JSX inside markdown. This includes importing and rendering React components!
    1. Styling a Reach component feels similar to styling any native element. There are no themes and you don't have to prescribe to any specific approach to styling. There are some basic styles to make the components usable off-the-shelf, but you can override and add to them with stylesheets, styled components, emotion, glamor, whatever you want.