snabbdom / snabbdom

A virtual DOM library with focus on simplicity, modularity, powerful features and performance.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JSX Conditional Rendering

bhainesva opened this issue · comments

Hello,

I'm wondering how to render things conditionally using the JSX syntax. I found this comment which suggested that the normal react syntax (bool && <Tag />) should work:

// for conditional rendering we support boolean child element e.g cond && <tag />

When I try this though, the boolean itself is getting rendered. For example:

const Component = () => {
  return <div>
    {false && <div>Hello World!</div>}
  </div>;
};

renders 'false'.

I've also tried this:

const Component = () => {
  return <div>
    {false ? <div>Hello World!</div> : null}
  </div>;
};

but that renders the string 'null'.

Here's a codepen reproduction: https://codepen.io/bhaines-yext/pen/LYjORYm. Am I doing something incorrectly?

Edit: I've messed around a little more and there are some interactions that I don't understand going on. For example here: https://codepen.io/bhaines-yext/pen/WNEXGor?editors=0010 currently nothing is rendered. But removing the <Component3 /> call from the Parent component causes false null to be rendered.

The workaround I've found that seems to work most consistently is using an empty array like:

const Component = () => {
  return <div>
    {false ? <div>Hello World!</div> : []}
  </div>;
};

Try using the jsx pragma provided by snabbdom instead of the snabbdom-jsx package.

/** @jsx snabbdom.jsx */
import * as snabbdom from "https://cdn.skypack.dev/snabbdom@3.1.0";

Here is a codepen reproduction. Hope this solves your problem.

Thank you that's what I was missing!