Viuu -a
Viuu -a

Reputation: 108

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.

Upvotes: 4

Views: 6081

Answers (3)

Tj Gienger
Tj Gienger

Reputation: 1405

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.

Upvotes: 1

Davet
Davet

Reputation: 332

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.

Upvotes: 2

Hyung Cho
Hyung Cho

Reputation: 127

You want to have your render function look something like this:

render: function () {
  return (
    {
      array.map(function (el, i) {
        var flag = 0;

        if (el.a1 || el.a2) {
          flag = 1;
          return <p>true flag enabled</p>;
        } else {
          return <p>...</p>;
        }
      }
    } 
  );
}

React allows you to return an array of React elements, so you can map your array and return a JSX element for every element of the array.

Upvotes: 0

Related Questions