ilyo
ilyo

Reputation: 36411

Inline if-else with big chunks of code in JSX

I have 2 chunks of code I want to switch between conditional and I prefer to do it inline, but it seems this syntax is not correct:

const chunk1 = (...)
const chunk2 = (...)

{this.state.condition ? (
  {chunk1}
) : (
  {chunk2}
)}

I get:

Uncaught Error: Objects are not valid as a React child (found: object with keys {loginOptions}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Card.

What would be the correct way?

Upvotes: 1

Views: 2308

Answers (3)

Jonathan Dion
Jonathan Dion

Reputation: 1671

I think your syntax is wrong. Try this instead:

{this.state.condition ? 
  chunk1
: 
  chunk2
}

Or

  if (condition) {
    content = chunk1;
  } else {
    content = chunk2;
  }

{content}

ES7 do:

const content = (data) => do {
  if (data) chunk1
  else chunk2
}

{content}

More info

Official React documentation for Conditional rendering

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 281892

Considering the chunk of code is JSX elements only, you can do it like

class App extends React.Component {
    state = {condition: false}
    
    render() {
      var chunk1 = (<div>Hello World</div>)
      var chunk2 = (<div>Hello React</div>)
      return (
          <div>{this.state.condition? chunk1 : chunk2}</div>
      )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 0

Taras Kovalenko
Taras Kovalenko

Reputation: 2393

I currently like to format my ternaries like this in react:

render () {
  return (
    <div className="row">
      { //Check if message failed
        (this.state.message === 'failed')
          ? <div> Something went wrong </div> 
          : <div> Everything in the world is fine </div> 
      }
    </div>
  );
}

Upvotes: 0

Related Questions