Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF block inside render function ReactJS

Am newbie to ReactJS. I want to use a IF block inside the render function. While search for this I got result like "You should use ternary operator instead of IF statement". But if I want to use something like,

$.each(array, function(i, x) {
  var flag = 0
  if({x.a1} || !{x.a2}) {
    flag = 1;
    <p>true flag enabled</p>
  }
  <p>...</p>
 });

How to convert this statement into JSX syntax or how to use it in React render fucntion.

Thanks in advance.

like image 812
Viuu -a Avatar asked Sep 15 '25 20:09

Viuu -a


2 Answers

This link will help you https://facebook.github.io/react/tips/if-else-in-JSX.html

But I'd use something like this, as its slightly easier to read (IMHO). Note, your array is a prop - passed into the component (or could be a state). I'd use lodash for mapping etc, cause its so useful all over the place (https://lodash.com/)

_renderElements: function(){

return _.map(this.props.array, function(el){
var flag = 0;

 return el.a1 || el.a2 ? <p>{'true  1 enabled'}</p> : <p>...</p>;


})

},
render: function () {
  return (
    {this._renderElements()}
    } 
  );
}

Hope that's helpful.

like image 169
Davet Avatar answered Sep 18 '25 17:09

Davet


I do this in one of two ways, depending mostly on how big the if statement is.

one scenario, I don't know if I'm going to render an element or not:

Component = React.createClass({
    render() {
        var elem;
        if (something) {
            elem = (<SomeOtherComponent />);
        }
        return (
            <div>{elem}</div>
        );
    }
});

This is basically a way to either show the element/component or not. If I'm going to map something I would use a separate method and call it:

Component = React.createClass({
    mapIt() {
        return this.props.items.map(item => {
            ... do your stuff ...
            return (
                <SomeOtherComponent prop1={item.value} ... />
            );
        });
    },

    render() {
        return (
            {this.mapIt()}
        );
    }
});

This to me is a nice clean way of handling.

like image 28
Tj Gienger Avatar answered Sep 18 '25 19:09

Tj Gienger