Skip to content Skip to sidebar Skip to footer

How To Use If Within A Map Return?

I need to generate diffrent reactJS code based on datamodel but I get In file '~/Scripts/Grid.jsx': Parse Error: Line 13: Unexpected token if (at line 13 column 15) Line: 52 Co

Solution 1:

You put return statement inside if clause like so:

    row = this.props.cells.map(function(cell, i) {

        if(cell.URL != null && cell.URL.length > 0){
            return<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>;        
        }
        else {
            return<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>;
        }

    }.bind(this));

Solution 2:

You could also use a ternary (inline if/else) statement. It might look like this:

row = this.props.cells.map(function(cell, i) {
    return (cell.URL != null && cell.URL.length > 0) ? 
        (<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>) :
        (<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>)
}.bind(this));

or es6

row = this.props.cells.map((cell, i) => (cell.URL != null && cell.URL.length > 0) ? 
        (<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>) :
        (<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>)
);

but, for readability, I would suggest nilgun's answer.

Although I would remove the else statement, since it is redundant. You could also remove the curly brackets, this is a matter of preference.

row = this.props.cells.map(function(cell, i) {
    if(cell.URL != null && cell.URL.length > 0)
        return<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>;        
    return<tdclassName={cell.Meta.HTMLClass}key={i}>{cell.Text}</td>;
}.bind(this));

Post a Comment for "How To Use If Within A Map Return?"