Skip to content

Instantly share code, notes, and snippets.

@rajadain
Created January 2, 2019 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajadain/5bf961ce975b143670bc2cd80b48c9bb to your computer and use it in GitHub Desktop.
Save rajadain/5bf961ce975b143670bc2cd80b48c9bb to your computer and use it in GitHub Desktop.
JSX Ternary Conditional Assignment

JSX Ternary Conditional Assignment

Straight

const legend = isCropLayerActive ? (
    <div
        className="layercontrol__legend"
        onMouseOver={disableMapZoom}
        onFocus={disableMapZoom}
        onMouseOut={enableMapZoom}
        onBlur={enableMapZoom}
    >
        {legendItems}
    </div>
) : null;
  • Easier to read
  • Does not add mental burden of inversion

Inverted

const legend = !isCropLayerActive ? null : (
    <div
        className="layercontrol__legend"
        onMouseOver={disableMapZoom}
        onFocus={disableMapZoom}
        onMouseOut={enableMapZoom}
        onBlur={enableMapZoom}
    >
        {legendItems}
    </div>
);
@kellyi
Copy link

kellyi commented Jan 25, 2019

There's an alternate possible form we could consider which is...

const legend = isCropLayerActive && (
    <div
        className="layercontrol__legend"
        onMouseOver={disableMapZoom}
        onFocus={disableMapZoom}
        onMouseOut={enableMapZoom}
        onBlur={enableMapZoom}
    >
        {legendItems}
    </div>
);

A falsy value for isCropLayerActive will make the whole thing falsy, which gets treated as null in the rendering.

@caseycesari
Copy link

caseycesari commented Feb 20, 2019

Alternatively:

// app.js
<parentComponent>
    <legend isLegendShown={isLegendShown} />
</parentComponent>

// legend.js
...

render() {
   if (this.props.isLegendShown) {
       return (
           <div
               className="layercontrol__legend"
               onMouseOver={disableMapZoom}
               onFocus={disableMapZoom}
               onMouseOut={enableMapZoom}
               onBlur={enableMapZoom}
           >
               {legendItems}
            </div>
        );
    } else {
        return null;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment