someuser2491
someuser2491

Reputation: 1968

How to use the jsx conditionals in react?

i want to render a button and a component when some condition is true within the render method.

Below is my code,

render = () =>  {
    <div>
        {(this.state.exists || this.state.active) &&
            <button>
                <svg>something</svg>
            </button>}
        {this.state.exists || this.state.active) &&
            <ChildComponent
                first_val={first_val}/>}
    </div>
}

The above code works. As you see from code above i am using the same condition to render or not the button and component. i am duplicating the condition. so i was trying to do it like below and it throws error of the curly bracket.

render = () =>  {
    <div>
        {(this.state.exists || this.state.active) &&
            <button>
                <svg>something</svg>
            </button>
            <ChildComponent
                first_val={first_val}/>}
    </div>
}

Is there a way to simplify this or better way of using conditionals here. Could someone provide an insight into this. thanks.

Upvotes: 0

Views: 41

Answers (2)

Quentin
Quentin

Reputation: 943569

An expression can only evaluate as one thing.

You're trying to create two things: a button and a child component.

You need to wrap them in a data structure such as a React.Fragment.

{
    (this.state.exists || this.state.active) &&
    <>
        <button>
            <svg>something</svg>
        </button>
        <ChildComponent first_val={first_val}/>
    </>
}

It's like returning an array [1, 2] instead of 1 2 from a function.

Upvotes: 3

Akhil Aravind
Akhil Aravind

Reputation: 6130

This is because sub elements elements need to be in a single element scope

try replacing your

render = () =>  {
    <div>
        {(this.state.exists || this.state.active) &&
            <button>
                <svg>something</svg>
            </button>
            <ChildComponent
                first_val={first_val}/>}
    </div>
}

with

render = () =>  {
        <div>
            {(this.state.exists || this.state.active) &&(
    <React.Fragment>
                <button>
                    <svg>something</svg>
                </button>
                <ChildComponent
                    first_val={first_val}/>
    </React.Fragment>
    )}
        </div>
    }

Upvotes: 1

Related Questions