Ajit
Ajit

Reputation: 675

Is there a better way to use conditionals inside jsx?

I've been learning React for the past few weeks and one thing that I don't like is that I have to use ternary operator for if else inside the render function.

Something like:

function render() {
    return (
        {x==="Let's go" ? <Go /> : <Hold on />}
    )
}

Is there a way I can use a traditional if-else or switch for that matter with jsx syntax in React?

Upvotes: 1

Views: 158

Answers (2)

Aaron Conran
Aaron Conran

Reputation: 321

I utilize a few approaches to clean up the render method of more complex components.

1) Use a variable. Before you are actually in the JSX portion (the return) you can use the flexibility of raw JS to build variables. To take your example...

function render() {
    let body;
    if (x === "Let's go") {
        body = <Go />
    } else {
        body = <Hold on />;
    }
    return (
        <div>
            {body}
        </div>
    );
}

Note that the top level needs to be wrapped, just put an extra div in there.

2) Use a function. This example is probably a little too simplistic but you'll get the idea..

renderBody() {
    let body;
    if (x === "Let's go") {
        body = <Go />
    } else {
        body = <Hold on />;
    }
    return (
        {body}
    )
}

render() {
    return (
        <div>
            {renderBody()}
        </div>
    )
}

3) Use an array (really a subset of #1) but oftentimes I find scenarios where sometimes I need to return 1 element but other times I need to return a variable number of elements. I will create an array at the top of the function and then push/unshift elements onto the array. Note that any time that you are building an array you must provide a key for each element so that React can update it properly.

let els = [
    <div key="always">Always here</div>
];
if (foo) {
    els.push(<div key="ifFoo">Conditionally Here</div>)
}

And then you just use the {els} variable in your main JSX.

4) Return null when you don't want anything to render

Upvotes: 2

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

I prefer this syntax

function render() {
    if (x==="Let's go") return <Go />;
    return <Hold on />;
}

Upvotes: 0

Related Questions