Daniel Moses
Daniel Moses

Reputation: 5858

React with multi element conditionals

I am converting an existing application into ReactJS. I have found something difficult to do well in ReactJS. Below is what I would like to do

render () { 
    return (<div id="container">
        <div className="shared">shared content here</div>
        <div className="shared">shared content here</div>
        <div className="shared">shared content here</div>
        {featureAEnabled ? 
        (<div className="featureA">featureA enabled content</div>
        <div className="featureA">featureA enabled content</div>) :
        (<div className="old">featureA disabled content</div>
        <div className="old">featureA disabled content</div>)
    </div>);
}

The issue is you cannot return multiple elements in React, you must always return a single element.

My current solutions involve

  1. Rewrite all my css to allow for elements to encapsolate any of these feature switches
  2. Do the following:

code:

render() { 
    return (<div id="container">
        <div className="shared">shared content here</div>
        <div className="shared">shared content here</div>
        <div className="shared">shared content here</div>
        {featureAEnabled && <div className="featureA">featureA enabled content</div>}
        {featureAEnabled && <div className="featureA">featureA enabled content</div>}
        {!featureAEnabled && <div className="old">featureA disabled content</div>}
        {!featureAEnabled && <div className="old">featureA disabled content</div>}
    </div>);
}

Is there a way to allow for codeblocks that are based on a condition and render multiple elements like in my first code snippet?

Upvotes: 1

Views: 64

Answers (2)

Upasana
Upasana

Reputation: 1975

Ideally you should try to separate 'featureAEnabled' and 'featureADisabled' elements in separate components and then render them.

Other way of doing that is to have your 'featureAEnabled' and 'featureADisabled' elements in an array and return it. Like below:

render() {
    let renderFeatureA = [
        <div >featureA enabled content</div>,
        <div >featureA enabled content</div>
    ];
    let disableFeatureA = [
        <div >featureA disabled content</div>,
        <div >featureA disabled content</div>
    ];

    let renderItems = featureAEnabled ? renderFeatureA : disableFeatureA;

    return (
    <div id="container">
        <div >shared content here</div>
        <div >shared content here</div>
        <div >shared content here</div>
        {renderItems}
    </div>
    )
};

Upvotes: 1

jmargolisvt
jmargolisvt

Reputation: 6088

One way to do this is to just toggle a class in your render.

let featureEnabledClasses = 'hidden';

if (myCondition === true) {
  featureEnabledClasses = '';
}

Then you can just serve up

<div className={featureEnabledClasses}>featureA enabled content</div>

Upvotes: 0

Related Questions