Search code examples
javascriptreactjscomponentsjsxternary

Ternary operator error... a valid React element must be returned?


I've got this simple exercise on react components to work with an if conditional but I wanted to try using a ternary operator instead. The problem is that now I get an error telling me: "TonightsPlan.render(): a valid React element must be returned..."

import React from 'react';
import ReactDOM from 'react-dom';

const fiftyFifty = Math.random() < 0.5;

// New component class starts here:
class TonightsPlan extends React.Component
  {
    render()
      {
        fiftyFifty ?
        <h1>Tonight I'm going out WOO</h1>:
        <h1>Tonight I'm going to bed WOOO</h1>;
      }
  };

ReactDOM.render(<TonightsPlan/>, document.body);

So I guess there's something wrong with the way I'm using the ternary operator here but I can't tell what it is... I could really use some help to figure that out, please!


Solution

  • Everything is fine, just the return in render is missing. J

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const fiftyFifty = Math.random() < 0.5;
    
    // New component class starts here:
    class TonightsPlan extends React.Component
      {
        render()
          {
            return (
              (fiftyFifty) 
                ? <h1>Tonight I'm going out WOO</h1>
                : <h1>Tonight I'm going to bed WOOO</h1>;
             )
          }
      };
    
    ReactDOM.render(<TonightsPlan/>, document.body);