React-React loops v1.3.0: React Loops — React Velcro Architecture

icon
Latest Release: v1.3.0

New:

  • Render a special case when a collection is empty with ifEmpty (#20)

Fixes:

  • Support older browsers by not using let (f47d563)
  • Fix TypeScript definitions by replacing React types with generic JSX types (#19)
Source code(tar.gz)
Source code(zip)

React Loops — React Velcro Architecture

Build Status Coverage Status

React Loops work alongside React Hooks as part of the novel React Velcro architecture for building sticky, secure user interfaces that don't come apart under pressure.

Version Changelog

Get started with Velcro by installing React Loops!

Install with yarn or npm.

yarn add react-loops

And import into your Javascript.

import { For } from 'react-loops'

React Loops comes ready with both Flow and TypeScript types for high quality integration into codebases that use these tools.

For-of Loops

Use the props of to provide the list and as to provide an element for each item in the list. The of prop accepts Arrays, Array-likes, and Iterables (such as Map, Set, and Immutable.js).

import { For } from 'react-loops'

function Bulleted({ list }) {
  return (
    <ul>
      <For of={list} as={item =>
        <li>{item}</li>
      }/>
    </ul>
  )
}

Or provide a "render prop" function as a child.

import { For } from 'react-loops'

function Bulleted({ list }) {
  return (
    <ul>
      <For of={list}>
        {item =>
          <li>{item}</li>
        }
      </For>
    </ul>
  )
}

For-in Loops

Use the prop in to provide an Object instead of an Array or Iterable.

import { For } from 'react-loops'

function BulletedDefinitions({ terms }) {
  return (
    <ul>
      <For in={terms} as={(item, {key}) =>
        <li>{key}: {item}</li>
      }/>
    </ul>
  )
}

Loop empty conditions

A common pattern when rendering a collection is to render a special case when the collection is empty. Optionally provide an ifEmpty prop to handle this case for both <For in> and <For of> loops.

The ifEmpty prop accepts anything renderable (strings, numbers, JSX) or a function which returns anything renderable.

import { For } from 'react-loops'

function BulletedWithFallback({ list }) {
  return (
     <ul>
      <For of={list} ifEmpty={<em>Nothing here!</em>}>
        {item =>
          <li>{item}</li>
        }
      </For>
    </ul>
  )
}

Loop iteration metadata

Access additional information about each iteration by destructuring the second callback argument:

  • index: A number from 0 to the length of the list
  • length: The length of the list
  • key: The key for this item in the list, same as index for Arrays but string Object properties for in loops
  • isFirst: True for the first iteration
  • isLast: True for the last iteration
import { For } from 'react-loops'

function BulletedSentence({ list }) {
  return (
    <ul>
      <For of={list} as={(item, { isLast }) =>
        <li>{isLast && "and "}{item}</li>
      }/>
    </ul>
  )
}

React Keys & Reorderable Collections

React Loops provides a key prop automatically on each child by default (by using the { key } loop iteration metadata). This is a great default if your collection will not later reorder and an ergonomic improvement over your trained muscle memory of adding key={i} to every list.map() return value.

However, reorderable collections should still directly provide the key prop on the element returned from the loop callback. Read more about Lists and Keys in the React documentation.

import { For } from 'react-loops'

function BulletedReorderable({ list }) {
  return (
    <ul>
      <For of={list} as={item =>
        <li key={item.id}>{item.label}</li>
      }/>
    </ul>
  )
}

What is React Velcro?

Only the newest, coolest, most blazing fast React architecture out there!

React Hooks has been an exciting development in the evolution of React, but it felt like it was only half of the story. React Loops completes the gripping picture by providing React's missing control-flow operators via JSX elements.

The React Velcro architecture was announced by @leebyron on April 1st, 2019.

Is this a Joke?

Take a look at this side by side with the old looping pattern and you tell me (hint).

But isn't this a React anti-pattern? Just go use Angular or Vue?

Yes, React Loops is directly inspired by Angular and Vue. It's also directly inspired by older XML component syntax like XSLT, JSTL, and E4X. These technologies all have their drawbacks, however we should not abandon all aspects of these ideas.

React Loops are not an anti-pattern. array.forEach() is not an anti-pattern despite the existence of the for..of loop and neither is <For>. React Loops follows React's model of components as encapsulation of behavior and state. It uses the "render prop" pattern, like react-router's <Route> component, itself reminiscent of XSLT.

React considers Angular (and Vue) directives as anti-patterns not because they emulate loops or control flow. It is because they affect scope in ways that removes the ability to use plain Javascript, requires a template language, and makes using other tools like ESLint difficult. They also are implemented as attributes (props) on any element which complicates type-checking and implementation.

React Loops avoids these drawbacks by providing <For> as a specific component with a clear signature and callback functions to produce each element for clear, "just Javascript," scoping rules avoiding the need for template languages or additional compilation.

Try React Loops in your project, you just might like it!

Are there any other libraries supporting that React Velcro architecture?

Yes

  • babel-plugin-jsx-control-statements is a Babel plugin with many control statements.

    Its <For> component suffers from some of the problems described above, caveat emptor.

  • react-condition contains the old <If>, <Else>, and <ElseIf> statements from this library, as well as some new ones such as <Switch>, <Case>, and <Default>.
  • react-for is a predecessor and a very similar idea which includes other variants of loops.
  • react-listable is a predecessor of this idea which includes <ol> and <ul> components.

Contributing & License

Contributions are welcome from all who follow the community code of conduct.

  1. Fork this repository
  2. yarn install
  3. Make your change in a branch
  4. Ensure your change includes any relevant tests, type definitions (TypeScript and Flow), and documentation.
  5. yarn test
  6. Create a pull request

React Loops is provided under the MIT license:

Copyright 2019 Lee Byron

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments

  • Compare with Swiftui's ForEach Component
    Compare with Swiftui's ForEach Component

    Jun 9, 2019

    This is not a real issue, but wanted to mention this. The recently announced SwiftUI framework by Apple has a ForEach component. Might be worthwhile to mention that in the README, as a validation of the general idea.

    https://developer.apple.com/documentation/swiftui/foreach

    Some example usage: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-views-in-a-loop-using-foreach

    Reply
  • React Router Route Component doesn't rerender and execute
    React Router Route Component doesn't rerender and execute

    Sep 3, 2019

    
    export const routes = [
      {
        path: '/',
        exact: true,
        component: PageIndex,
        private: true
      },
      {
        path: '/login',
        exact: true,
        component: PageLogin
      },
    ]
    export const PrivateRoute = ({ component: Component, ...remaining }) => {
      const { authenticated } = useAuthDataContext();
      return (
        <Route
          render={props =>
            authenticated ? <Component {...props} /> : <Redirect to="/login" />
          }
          key={remaining.path}
        />
      );
    };
    
    // BUGS OUT WITH ROUTING
    // export const renderRoutes = routes => (
    //   <For
    //     of={routes}
    //     as={route =>
    //       route.private ? (
    //         <PrivateRoute {...route} key={route.path} />
    //       ) : (
    //         <Route {...route} key={route.path} />
    //       )
    //     }
    //   />
    // );
    // export const renderRoutes = routes => (
    //   <For of={routes}>
    //     {route =>
    //       route.private ? (
    //         <PrivateRoute {...route} key={route.path} />
    //       ) : (
    //         <Route {...route} key={route.path} />
    //       )
    //     }
    //   </For>
    // );
    export const renderRoutes = routes =>
      routes.map(route =>
        route.private ? (
          <PrivateRoute {...route} key={route.path} />
        ) : (
          <Route {...route} key={route.path} />
        )
      );
    
    

    Last one works but the others not.

    This is using the basic redirect on react-router to check if user is authenticated.

    Any ideas why it doesn't get redirected when using the two above.

    Reply
  • Fix generic constraint for O
    Fix generic constraint for O

    Apr 3, 2019

    TypeScript's object type is lowercase; the pascal-case version refers specifically to instances of the Object constructor.

    It's almost the same until you have some field whose type conflicts with a field from Object.prototype.

    Reply
  • 📝 Add react-condition to the list of libraries
    📝 Add react-condition to the list of libraries

    Apr 8, 2019

                                                                                                                                                                                                           
    Reply
  • Implement do-while
    Implement do-while

    Apr 2, 2019

    Lack of do-while severely hurts React adoption. It has been proven that almost always you enter a loop at least once, there is no sane reason to check if you will enter a loop at all on first invocation. Do-while is much more performant than a for loop that this will also allow us that the clock cycles we lose with immutablejs can be obtained from the additional CPU power this feature would bring, making immutablejs more popular.

    Reply
  • adds a hint
    adds a hint

    Apr 2, 2019

    for all the beginners

                                                                                                                                                                                                           
    Reply
  • react-loops === react-listable ?
    react-loops === react-listable ?

    Apr 5, 2019

    What's the difference between lib and yours? It seems like a fork.

    Reply
  • I built a similar library a little while back
    I built a similar library a little while back

    Apr 2, 2019

    Hey 👋

    Funny enough, I built a similar library for writing loops in JSX a few months ago: https://github.com/MJez29/react-for. I was wondering if you had any thoughts on my implementation vs your version 👀

    Thanks 😄

    Reply
  • What's the benefit this library bring to react?
    What's the benefit this library bring to react?

    Apr 2, 2019

    Is this just syntax sugar for loop? Lol I never thought React Dev favor a angularjs and Vue ish syntax, which I would run far away from because it's adding unnecessary syntax sugar above .map which is completely easy to understand as it's just JS!

    sorry I am just not buying it lol but maybe someone will enjoy it? Then may as well go to code with Vue or angularjs lol

    Reply
  • RFC: Remove <If>
    RFC: Remove

    Apr 2, 2019

    I think <If> and <Else> might be a distraction from the value of <For> and I'm considering remove it. They're also potentially helpful for clearer syntax compared to {condition && <Node />} but have some real drawbacks as well.

    Perhaps we should consider including them in a react-conditionals library?

    Reply
  • Added Choose/When/Otherwise components inspired by XSL
    Added Choose/When/Otherwise components inspired by XSL

    Apr 1, 2019

    Added super useful Choose/When/Otherwise components as discussed on Twitter

    Reply
  • feat: add fallback UI prop
    feat: add fallback UI prop

    Apr 5, 2019

    In actual development, We usually have to judge whether the array or object passed in is empty. If it is empty, we need to display the fallback UI.

    Reply