GithubHelp home page GithubHelp logo

romac / react-if Goto Github PK

View Code? Open in Web Editor NEW
1.0K 11.0 51.0 18.39 MB

πŸŒ— Render React components conditionally

Home Page: https://romac.github.io/react-if/

License: MIT License

JavaScript 1.39% TypeScript 98.61%
react

react-if's Introduction

React If

npm npm bundle size Continuous Integration Issues License Contact Contact

Render React components conditionally.

What does this component do

Take a look at the following presentational component, which contains a commonly used pattern for conditional rendering:

const Bar = ({ name, age, drinkingAge }) => (
  <div>
    <Header />
    {age >= drinkingAge ? <span className="ok">Have a beer, {name}!</span> : <span className="not-ok">Sorry, {name}, you are not old enough.</span>}
    <Footer />
  </div>
);

With React-If you can rewrite this into a more readable, expressive format:

const Bar = ({ name, age, drinkingAge }) => (
  <div>
    <Header />
    <If condition={age >= drinkingAge}>
      <Then>
        <span className="ok">Have a beer, {name}!</span>
      </Then>
      <Else>
        <span className="not-ok">Sorry, {name}, you are not old enough.</span>
      </Else>
    </If>
    <Footer />
  </div>
);

Delaying evaluation of children / condition

It is important to note that, because JavaScript is an eagerly evaluated language, children of both the Then and Else component and condition will be evaluated regardless of the value of the condition. Should that be an issue for performance reasons, one can wrap said children / condition in a arrow function, to delay evaluation of the children / condition, as in the following example:

const renderData = (data) => {
  val computed = /* expensive computation */
  return <span>Here is the result: {computed}</span>;
};

const Foo = ({ data }) => (
    <div>
        <If condition={false}>
            <Then>{() =>
              renderData(data)
            }</Then>
            <Else>
              Nothing to see here
            </Else>
        </If>
        <If condition={!props.bears}>
          <Then>
            No bears
          </Then>

          <Else>
            <If condition={() => props.bears.length}>
              Empty bears array
            </If>
            <Else>
              // Display bears
            </Else>
          </Else>
        </If>
    </div>
)

By doing so, renderData will not be called in the 1st example.

And props.bears.length will not be called in the 2nd example.

Installing and usage

NPM:

npm install react-if Or with yarn: yarn add react-if

// ES2015
import { If, Then, Else, When, Unless, Switch, Case, Default } from 'react-if';

// CommonJS:
const { If, Then, Else, When, Unless, Switch, Case, Default } = require('react-if');

Examples

Switch/Case/Default

import React from 'react';
import { Switch, Case, Default } from 'react-if';

const myNumber = 3;

const Example = () => (
  <div>
    <Switch>
      <Case condition={myNumber === 9}>This will be displayed if condition is matched</Case>
      <Case condition={myNumber > 1}>This will be displayed if condition is matched</Case>
      <Default>This will be displayed if no Case have matching condition</Default>
    </Switch>
  </div>
);

Shorthands: When and Unless

import React from 'react';
import { When, Unless } from 'react-if';

const someCondition = false;

const Example = () => (
  <div>
    <When condition={someCondition}>This will only be displayed, if the condition is TRUE</When>
  </div>
);

const AnotherExample = () => (
  <div>
    <Unless condition={someCondition}>This will only be displayed, if the condition is FALSE</Unless>
  </div>
);

Asynchronous condition

import React from 'react';
import { If, Fallback, Then, Else } from 'react-if';

const Example = () => {
  const fetchData = () => {
    // Return promise
  };

  return (
    <div>
      <If condition={fetchData()}>
        <Fallback>Loading data ...</Fallback>
        <Then>
          {(data) => (
            <span>Here is your data: {data}</span>
          )}
        </Then>
        <Else>
          {(error) => (
            <span>Failed to load data because "{error}"</span>
          )}
        </Else>
      </If>
    </div>
  );
});

API

Note: For a fully auto-generated API, see the github pages website

<If />

Property Type Default
condition Boolean/Promise
keepAlive Boolean false

If condition evaluates to true, renders the <Then /> block will be rendered, otherwise renders the <Else /> block. Either block may be omitted.

This component can contain any number of <Then /> or <Else /> blocks, but only the first block of the right type (either Then or Else, depending on the condition) will be rendered.

When passing a Promise to condition, renders the Fallback block while the Promise is pending, the <Then /> block once Promise is resolved, and the <Else /> block when Promise is rejected. The return value of the Promise can be retrieved within the <Then /> and <Else /> blocks; a render function must be child of these blocks.

<Then>{(returnValue, promiseHistory, cancellablePromise) => <span>{returnValue}</span>}</Then>

The parameters of this render function are:

  • returnValue: The return value of the Promise (for the <Then /> block) or the error (for the <Else /> block);
  • promiseHistory: an Array of all the Promises that were ever passed to <If />. It contains cancellablePromise Objects, that have a promise, as well as a cancel method used to cancel the promise;
  • cancellablePromise: the cancellablePromise Object containing the promise that caused the rendering of this <Then />|<Else /> block;

If the keepAlive prop evaluates to false, each rerender of the <If /> component will automatically ignore the previous Promise if it was still pending.

<Then />

Can contain any number of elements inside, which it renders as-is. It can also contain a function. Should not be used outside of an <If /> block. It will only be displayed, if parent If block's condition is true.

<Else />

Can contain any number of elements inside, which it renders as-is. It can also contain a function. Should not be used outside of an <If /> block. It will only be displayed, if parent If block's condition is false.

<Switch />

A container for <Case condition={...}/> and <Default /> blocks. It will render the first matching Case, or the first encountered Default (, or null).

<Case />

Property Type
condition Boolean

If the Case is the first one to have its condition evaluates to true inside the parent <Switch /> it will be the only rendered.

<Default />

If no Case have its condition evaluates to true inside the parent <Switch />, the first Default will be the only one rendered.

<When />

A shorthand for <If condition={...}><Then>...</Then></If>. The same rules apply to the child elements as with using the Then block.

<Unless />

A shorthand for <If condition={...}><Else>...</Else></If>. The same rules apply to the child elements as with using the Else block.

License

React If is released under the MIT license.

Contributors

Please make sure to read the Contributing Guide before making a pull request.

Thank you to all the people who already contributed to react-if!

react-if's People

Contributors

ako520 avatar arcath avatar artcoding-git avatar dependabot[bot] avatar depfu[bot] avatar ejbp avatar eropple avatar favna avatar fc5570 avatar girlbossrush avatar gradosevic avatar haroenv avatar iwfan avatar mamoru1234 avatar martijnthe avatar melyourhero avatar meszaros-lajos-gyorgy avatar msftenhanceprovenance avatar renovate-bot avatar renovate[bot] avatar rleahy22 avatar romac avatar sawa-ko avatar theo-js avatar timjacobi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-if's Issues

If/Else does not catch all scenarios

I have ran into a scenario that react-if doesn't seem to handle appropriately.

console.log(this.props.ticket); // Output = null

<If condition={this.props.ticket === 'null' || null}>
    <Then>
        <div id="noData" style={style.noData}>
            No details found for the given ticket
        </div>
    </Then>
    <Else>
        {this.props.ticket.map(function(data,i) {
            return (
                // Do something with this.props.ticket here
            )
        }, this)}
    </Else>
</If>

In my case, I have a props which has been verified to be equal to null. As seen above, I have created an if condition to not show data if the props is null.

However, regardless of this logic, the this.props.ticket.map inside <Else> is run in all cases. This then leads to a TypeError: Cannot read property 'map' of null error which prevents our app from rendering.

JavaScript is executing within If block before condition is considered

Here's the issue:

<If condition={1==2}>
  <Then>
     <div>
       {console.log('I dont want to see this.');}
     </div>
  </Then>
</If>

console shows -> I dont want to see this.

However, if you do this the React way, no console.

{1==2 && 
  <div>
    {console.log('I dont want to see this.');}
  </div>
}

I ran into this issue while creating my own <Condition> component. I don't know if this is something you can solve, but may lead to issues if you can't.

Allow non-booleans in the `condition` prop as a convenience

I see a lot of these warnings:

Warning: Failed prop type: Invalid prop `children` supplied to `If`.

Because I will have conditions that look like:

<When condition={state.data && state.data.myProfile}>
  My profile loaded!
</When>

With state.data.myProfile being an object that might look like:

{
  "id": 123,
  "name": "Joe",
  "email": "[email protected]"
}

Which means that I have to do this to silence warnings:

<When condition={!!(state.data && state.data.myProfile)}>
  My profile loaded!
</When>

Or:

<When condition={state.data && state.data.myProfile && true}>
  My profile loaded!
</When>

Both of these solutions seems solvable if react-if accepted non-boolean conditions.

null and undefined or anything non-truthy would be evaluated to a false.

React 18

With React 18 types, <If> has an issue. I get the following error
TS2559: Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update dependency @types/node to ^20.14.0
  • chore(deps): update dependency @testing-library/react to v16

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/continuous-delivery.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/continuous-integration.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/labelsync.yml
  • actions/checkout v4
  • crazy-max/ghaction-github-labeler v5
npm
demo/package.json
  • autoprefixer ^10.4.19
  • daisyui ^4.11.1
  • parcel ^2.12.0
  • postcss ^8.4.38
  • tailwindcss ^3.4.3
  • typescript ^5.4.5
package.json
  • @commitlint/cli ^19.3.0
  • @commitlint/config-conventional ^19.2.2
  • @favware/cliff-jumper ^3.0.3
  • @sapphire/eslint-config ^5.0.4
  • @sapphire/prettier-config ^2.0.0
  • @sapphire/ts-config ^5.0.1
  • @testing-library/jest-dom ^6.4.5
  • @testing-library/react ^15.0.7
  • @types/node ^20.13.0
  • @types/react ^18.3.3
  • @types/react-dom ^18.3.0
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • cz-conventional-changelog ^3.3.0
  • dts-cli ^2.0.5
  • eslint ^8.57.0
  • eslint-config-prettier ^9.1.0
  • eslint-config-react-app ^7.0.1
  • eslint-plugin-import ^2.29.1
  • eslint-plugin-jsx-a11y ^6.8.0
  • eslint-plugin-prettier ^5.1.3
  • eslint-plugin-react ^7.34.2
  • eslint-plugin-react-hooks ^4.6.2
  • lint-staged ^15.2.5
  • prettier ^3.3.0
  • react ^18.3.1
  • react-dom ^18.3.1
  • ts-jest ^29.1.4
  • typedoc ^0.25.13
  • typescript ^5.4.5
  • react ^16.x || ^17.x || ^18.x
  • prettier ^3.3.0
  • @types/react-dom ^18.3.0
  • @types/react ^18.3.3
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • cz-conventional-changelog ^3.3.0
  • eslint-config-prettier ^9.1.0
  • eslint-config-react-app ^7.0.1
  • eslint-plugin-import ^2.29.1
  • eslint-plugin-jsx-a11y ^6.8.0
  • eslint-plugin-prettier ^5.1.3
  • eslint-plugin-react-hooks ^4.6.2
  • eslint-plugin-react ^7.34.2
  • eslint ^8.57.0
  • react-dom ^18.3.1
  • ansi-regex ^5.0.1
  • minimist ^1.2.8
  • react ^18.3.1
  • yarn 4.2.2

  • Check this box to trigger a request for Renovate to run again on this repository

PropTypes

Can you include array in Then or Else proptypes?

Then.propTypes = Else.propTypes = {
children: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.number,
PropTypes.arrayOf(PropTypes.element),
PropTypes.object
])
};

My problem:


<If condition={true}>
 <Then>
   <Loading   />
 </Then>
 <Else>
   <div></div>
   <OtherComponent/>
 </Else>
</If>

Support promise condition

Motivation: When the condition is a Promise or an asynchronous callback, we cannot get the result immediately and have to wrap the children in another high order component. I think this is exactly the reason why I need an <If> component.

So I suggest the <If> component to support asynchronous conditions:

<If condition={Promise.resolve(true)}>
  The promise is resolved with `true`.
</If>

Then and Else have different allowance for child nodes

Hi,

Consider the following snippet:

<If condition={ parseInt(Math.random() * 100) % 2 == 0 }>
   <Then>{ "They killed Kenny!" }</Then>
   <Else>{ "You don't win friends with salad" }</Else>
</If>

Then works very well with single text fragment, however Else does not.

Uncaught Error: Else.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Lazy condition ?

When typing :

if (!a) {
  console.log('hey')
} else {
  if(a.length) {
    console.log('ho')
  } else {
    console.log('ha')
  }
}

You have no chance to get

Cannot read "length" of undefined

But with React-if :

<If condition={a}>
  <Then>null</Then>
  <Else>
    <If condition={a.length}>
      <Then>null</Then>
      <Else>null</Then>
    </If>
  </Else>
</If>

You'll get this error if a is undefined, for example.

Making the condition possibly-lazy (evaluated in a function), just like the render children; would be a solution.
Furthermore, it wouldn't break the current API

Warning: React.PropTypes.component will be deprecated in a future version. Use React.PropTypes.element instead.

I tried your plugin and got the error.

Warning: React.PropTypes.component will be deprecated in a future version. Use React.PropTypes.element instead.
app.js:21227 Warning: Required prop `condition` was not specified in `If`. Check the render method of `Dashboard`.
app.js:21227 Warning: Invalid prop `0` supplied to `If`. Check the render method of `Dashboard`.

You could make changes to the plugin to work correctly with the new version of React?

P.S. My package.json

"react": "^0.12.1",
"react-if": "^1.0.2",

Missing type definition in types.d.ts file

missing the following definitions

export class Switch extends React.Component { }
export class Case extends React.Component<IfOptions, any>{ }
export class Default extends React.Component { }

Doesn't work with browserify

/Users/thomas/Desktop/shopify-react/node_modules/react-if/index.js:85
})(window, typeof require === 'function' ? require('react') : window.React);
   ^
ReferenceError: window is not defined
    at Object.<anonymous> (/Users/thomas/Desktop/shopify-react/node_modules/react-if/index.js:85:4)
    at Module._compile (module.js:456:26)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/thomas/Desktop/shopify-react/node_modules/node-jsx/index.js:26:12)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/thomas/Desktop/shopify-react/react/components/DelegateProduct.react.js:2:10)
    at Module._compile (module.js:456:26)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/thomas/Desktop/shopify-react/node_modules/node-jsx/index.js:26:12)

bug: Geting Error : Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.

First of all, I am creating the app using Next.js 13 with the app directory. During development I get an error while I use Switch, Default, and Case components from React-if and the error says:

" Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead. "

Here is my code:

code

and when I delete the React-if component then the error disappears.

Also, regarding this announcement (reactjs/rfcs#107) that is true defaultProps will be moved to class render in React.

So can anyone update the module or tell me how to fix this error manually?

Thanks

It could be better optimized for browserify-shim

I've installed the library to node packages, and used it with browserify-shim. I have this syntax in package.json:

 "browserify-shim": {
 "react-if":{
      "exports":"ReactIf"
    },
  "client": {
      "exports": "Client",
      "depends": [
        "react:React",
        "react-dom:ReactDOM",
        "react-if:ReactIf"
      ]
    }
}

In my client file, I have to add these lines on top of the file in order to make it work:

var If = ReactIf.If;
var Then = If.Then;
var Else = If.Else;

It would be nice to define these variables directly in package.json

[Suggestion]: Take over maintenance (to support the community)

Hello Romac, I'm a great fan of this library and use it in several projects. However as you listed in the repo's description, you are no longer maintaining it.

For everyone in the community that uses your package (which is a lot if download count is anything to go by: https://www.npmtrends.com/react-if) I want to propose that I'd take over maintenance.

If you're up for this process, I have also attempted to contact you on Twitter (my handle is @favna_) and I would suggest we talk further details there, privately.

Unable to handle null

Previously discussed under Issue #18, I have a scenario that react-if doesn't seem to handle appropriately.

console.log(this.props.ticket); // Output = null

<If condition={this.props.ticket === 'null' || null}>
    <Then>
        <div id="noData" style={style.noData}>
            No details found for the given ticket
        </div>
    </Then>
    <Else>
        {this.props.ticket.map(function(data,i) {
            return (
                // Do something with this.props.ticket here
            )
        }, this)}
    </Else>
</If>

In my case, I have a props which has been verified to be equal to null. As seen above, I have created an if condition to not show data if the props is null.

However, regardless of this logic, the this.props.ticket.map inside <Else> is run in all cases. This then leads to a TypeError: Cannot read property 'map' of null error which prevents our app from rendering.

From the previous discussion, this is due to React having eager evaluation. It was suggested that we re-write our component to be like so:

<If condition={this.props.ticket === null}>
    <Then>
        <div id="noData" style={style.noData}>
            No details found for the given ticket
        </div>
    </Then>
    <Else>{function() {
        return this.props.ticket.map(function(data,i) {
            return (
                // Do something with this.props.ticket here
            )
        }, this)
    }}</Else>
</If>

Unfortunately, this does not work either and being unable to check for null has become a blocker for multiple areas of our project.

Any additional suggestions for getting around this issue? Is this something that React-if could gracefully catch?

if/then/else is not compatible with Ant Design's Form

First of all, I realy love this package.
But today I found that it's not compatible with Ant Design's Form, more accurately, the component Form.Item innner If/Else/Then can't be collected by Ant Design's Form. I hope that somebody can tell me if it should be resolved by "react-if"? Or maybe I should ask the Ant Design's developer for help?

As what I list, the ternary operator works well with Ant Design (Ant Design is a UI component framework which is widely used.οΌ‰
image

Implement different patterns

For lazy evaluation, we're currently implenting a pattern called "render prop" in a special mood which makes the children prop as-a-function.

import { When } from 'react-if'

const MyConditionalComponent = () => (
  <When condition={aBoolean}>
    {() => <ExpensiveComponent />}
  </When>
)

There are 2 other interesting patterns, that would be worth a try :

  • The "standard" render-prop

    import { When } from 'react-if'
    
    const MyConditionalComponent = () => (
      <When
        condition={aBoolean}
        render={() => <ExpensiveComponent />}
      />
    )
    
  • The HoC

    import { withWhen } from 'react-if'
    
    const MyConditionalComponent = () => {
      const ExpensiveComponentWhenRelevant = withWhen(
        aBoolean,
        ExpensiveComponent
      )
    
      return <ExpensiveComponentWhenRelevant />
    }
    

In our special case, I think the HoC look akward. Though, the standard render-prop would be useful, especially for cases like When or Case when the "enclosing" tag looks a little bit overkill.

What do you think ?


EDIT: to expand on it, there is a fourth interesting pattern used by react-router. I don't know it's name but it's a simpler one.

  • The lazy component

import { When } from 'react-if'

const MyConditionalComponent = () => (
  <When
    condition={aBoolean}
    component={ExpensiveComponent}
  />
)

It defers (kinda delegate) the instanciation of the underlying component (and postpone it by the way, which makes it naturally lazy)

I think this one could be interesting too

! Build fails

The issue name is self explainatory: travis fails to build due to outdated dependencies in the repo.

Travis fails with the following message:

Error: react-addons-test-utils is an implicit dependency in order to support [email protected]. Please add the appropriate version to your devDependencies. See https://github.com/airbnb/enzyme#installation

Also, node 5 and 6 should be updated too.

bug: Will generate a component instance no matter what the condition is

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

Will generate a component instance no matter what the condition is

Steps To Reproduce

image

image

Expected behavior

It costs to much, you should just use a function to wrap to to prevent the instance generation.

Screenshots

No response

Additional context

No response

bug: type inference

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

For example, if we have an article const being Article | null:

<If condition={article === null}>
  <Then>
    <NoArticle />
  </Then>

  <Else>
    {article.title} <---- TypeScript error because article is possibly null
  </Else>
</If>

Steps To Reproduce

Try to infer type.

Expected behavior

article type should be infered as Article as we already checked the null case.

Screenshots

No response

Additional context

No response

Expressions are still executed in a failed <If>

Here's a common use case for an if component - checking if something exists before looping through it, e.g. data from a server that could be an array but also could be empty.

const data = null

<If condition={data}>
   <p>I will not render as expected</p>
   {data.map((item) => // this line executes anyway, causing a crash
        ....
   )}
</If>

Even though the condition worked as expected, stoping the <p> from rendering, the expression is executed anyway?

Migrate to React 15.5+

Current codebase is still using React.PropTypes, instead if should reference PropTypes from prop-types package. This will break with next React release.

Should allow multiple JSX nodes within Then and Else

Thanks for the wonderful library.

Can we please allow constructs such as

<Then>
<div>Content 1</div>
<div>Content 2</div>
</Then>

in both Then and Else

Instead of having to do the following

<Then>
<span>
<div>Content 1</div>
<div>Content 2</div>
</span>
</Then>

request: React-if is not code coverage friendly

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

I am annoyed that react-if does not present itself as a branch in the code between if else and when and unless, for code coverage tools. && is treated as a branch where as a when is not.

Desired solution

Is it possible to code the implementation of the children of the conditional components to come up as branches in c8 coverage tooling. otherwise we cannot use react-if for serious projects

Alternatives considered

Removing react-if and just using && and || logic again

Additional context

No response

re-render bug

Hi,
Why when the "if" tag condition is false it will render the "Then" Tag? that's too much re-rendering...

Error upgrading to v3.2.0

I didn't make any change in my code. Just updated package from 3.1.3 to 3.2.0 and I'm getting this error at Bowser Console.

app.js:10124 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file its defined in. Check the render method of If.
    in If (created by PageFooter)
    in div (created by PageFooter)
    in div (created by PageFooter)
    in footer (created by PageFooter)
    in PageFooter (created by Connect(PageFooter))
    in Connect(PageFooter) (created by App)
    in div (created by App)
    in div (created by App)
    in DocumentTitle (created by SideEffect(DocumentTitle))
    in SideEffect(DocumentTitle) (created by App)
    in App (created by Connect(App))
    in Connect(App)
    in Provider

app.js:10294 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file its defined in. Check the render method of If.
    at invariant (http://localhost:5000/app.js:10294:16)
    at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (http://localhost:5000/app.js:25172:56)
    at ReactCompositeComponentWrapper.performInitialMount (http://localhost:5000/app.js:25596:23)
    at ReactCompositeComponentWrapper.mountComponent (http://localhost:5000/app.js:25487:22)
    at Object.mountComponent (http://localhost:5000/app.js:17982:36)
    at ReactDOMComponent.mountChildren (http://localhost:5000/app.js:24634:45)
    at ReactDOMComponent._createInitialChildren (http://localhost:5000/app.js:21718:33)
    at ReactDOMComponent.mountComponent (http://localhost:5000/app.js:21537:13)
    at Object.mountComponent (http://localhost:5000/app.js:17982:36)
    at ReactDOMComponent.mountChildren (http://localhost:5000/app.js:24634:45)

app.js:14605 Uncaught TypeError: Cannot read property __reactInternalInstance$t7ajv2eucf of null
    at Object.getClosestInstanceFromNode (app.js:14605)
    at findParent (app.js:28238)
    at handleTopLevelImpl (app.js:28267)
    at ReactDefaultBatchingStrategyTransaction.perform (app.js:18964)
    at Object.batchedUpdates (app.js:28192)
    at Object.batchedUpdates (app.js:17634)
    at dispatchEvent (app.js:28347)

Could this be a conflict with other outdated package? I'm using react 15.6.2.

Add support for lazy evaluation of children

Motivation: Children of both the Then and Else branch are currently being eagerly evaluated regardless of which branch will eventually be rendered. See issue #1 for more details.

The idea suggested by @tlrobinson is to wrap children of both branches in an anonymous function that will be called only if the branch is to be rendered based on the condition:

<If condition={cond}>
    <Then>{() => <Foo />}</Then>
    <Else>{() => <Bar />}</Else>
</If>

We might also want to support both styles (with or without the function), to lighten the syntax a bit when there is eg. no performance concern:

<If condition={cond}>
    <Then>{() => <BigComponent />}</Then>
    <Else>That was quick!</Else>
</If>

Lazy-loading children

I've noticed that if I use:

let myVariable = "not an array"
<When condition={_.isArray(myVariable)}>
    <MyComponent arrayProp={myVariable} />
</When>

React will warn that MyComponent's arrayProp has received a non-array value when I expect to not be called until _.isArray(myObject) is true.

If I use the strategy below, I get the expected result.

let myVariable = "not an array"
<When condition={_.isArray(myVariable)} 
            children={() => <MyComponent arrayProp={myVariable} />} 
/>   

If my second example is the appropriate way to do this, is the same possible with other components such as <If />, `, etc..?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.