• Stars
    star
    1,166
  • Rank 39,890 (Top 0.8 %)
  • Language
    JavaScript
  • Created over 5 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React Loops works with React Hooks as part of the React Velcro Architecture

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.

More Repositories

1

testcheck-js

Generative testing for JavaScript
JavaScript
1,184
star
2

iterall

🌻 Minimal zero-dependency utilities for using Iterables in all JavaScript environments.
JavaScript
815
star
3

async-to-gen

⌛ Use async functions in your JavaScript today with speed and simplicity.
JavaScript
506
star
4

spec-md

📖 Additions to Markdown for writing specification documents
HTML
380
star
5

streamgraph

Processing applet which creates the images seen in the Streamgraph paper
Java
281
star
6

ecmascript-more-export-from

Proposal: add more export-from statements in ES7
153
star
7

mesh

Processing library for creating point meshes.
Java
97
star
8

rollup-plugin-flow

Rollup plugin for removing Flow type annotations.
JavaScript
80
star
9

4000

63
star
10

cocoa-oauth2

Cocoa library for handling oauth2
59
star
11

til

Today I Learned
JavaScript
55
star
12

interactive-script

Easy to write interactive scripts
JavaScript
52
star
13

ecmascript-iterator-hof

Higher Order Functions on Iterators
JavaScript
42
star
14

rollup-plugin-async

Transforms Async functions to generator functions before bundling.
JavaScript
40
star
15

ecmascript-reverse-iterable

ReverseIterable Interface Spec Proposal
JavaScript
30
star
16

keyboard

My keyboard config
30
star
17

anyconnect-dark

Dark OSX menu bar assets for Cisco AnyConnect VPN.
24
star
18

mocha-check

Generative property testing for Mocha
17
star
19

bigtype

💥 Type big stuff
HTML
17
star
20

huron.wedding

Our wedding site
HTML
16
star
21

centerclock

A generative abstract clock.
JavaScript
13
star
22

fb-notify

Objective-C
12
star
23

grunt-jest

Grunt task for running jest tests.
JavaScript
12
star
24

respectify

Replaces the term 'politically correct' with 'respectful of other people' because it makes you oddly happy.
JavaScript
12
star
25

jasmine-check

Generative property testing for Jasmine
11
star
26

loda-js

Use JavaScript functionally, you shall.
JavaScript
10
star
27

ofxSDL

Overrides the openFrameworks windowing system to use SDL rather than GLUT.
C++
9
star
28

unflowify

Browserify transform for removing Flow type annotations.
JavaScript
9
star
29

fb-cocoa

Objective-C
8
star
30

remark-comment

Remark plugin to support comments
JavaScript
7
star
31

bubbletype

JavaScript
7
star
32

advent-of-code-2016

Solutions to the Advent of Code 2016 puzzles
JavaScript
6
star
33

dotfiles

JavaScript
6
star
34

ecmascript-reduced

Proposal for short-circuiting Array.prototype.reduce()
JavaScript
4
star
35

leebyron.github.io

Who has business cards anymore?
TypeScript
4
star
36

shapetween

(ARCHIVED 2007) Processing Library for tween and shape curves
Java
4
star
37

Wesley

Snipes
JavaScript
3
star
38

dbmd

Dropbox Hosted Markdown based CMS
JavaScript
3
star
39

iFBG

3
star
40

chain-js

A reactive framework.
JavaScript
2
star
41

cocoa-fbg

2
star
42

of-xcode-templates

openFrameworks XCode Templates
C++
2
star
43

shitty-peg

A Shitty PEG Parser
JavaScript
2
star
44

codespaces-dotfiles

Shell
2
star
45

lisp

Let's Learn Lisp with Lee
JavaScript
1
star
46

phagos

Button Mashing Glutton
C++
1
star
47

nuri-dog

http://nuri.dog
HTML
1
star
48

cocoa-net-connection

Cocoa class which monitors net connectivity
Objective-C
1
star
49

lrumap

JavaScript
1
star