Cody
Cody

Reputation: 915

ReactJS web site implementation error with multiple elements return

I tried the below code example 01 from reactjs.org and its working fine, But when I tried adding multiple elements (example 02) to return with this component it doesn't work.

Example 01

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }


  render() {
    if (this.state.liked) {
      return 'You liked this.';
    }

    return e( 
        'button',
          { onClick: () => this.setState({ liked: true }) },
        'Like'  
    );
  }
}

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

Example 02

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }


  render() {
    if (this.state.liked) {
      return 'You liked this.';
    }

    return e(
        <div> 
          <a href="#" >Login</a>
          <a href="#" >Logout</a>
        </div>
    );
  }
}

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

PS: I'm a newbie to reactJS and appreciate any help on this. Thanks.

Upvotes: 1

Views: 92

Answers (1)

Dario
Dario

Reputation: 6280

You are calling createElement with wrong syntax; here's the signature:

React.createElement(
  type,
  [props],
  [...children]
)

In your case, the right call would be

return e(
  'div',
  null,
  [
    e('a', { href: '#' }, 'Login'), 
    e('a', { href: '#' }, 'Logout')
  ]
);

However you could directly return HTML with no need of using createElement, just change the render to:

return (
  <div> 
    <a href="#" >Login</a>
    <a href="#" >Logout</a>
  </div>
);

Upvotes: 1

Related Questions