ReactJS onClick without JSX

Viewed 181

I am new to React and trying to set the onClick property of a react component but get the following error:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: <ul />. Did you accidentally export a JSX literal instead of a component?

My code is currently as follows:

// Navbar Component
class Navbar extends React.Component {

  constructor(){
    super();
    this.onItemClick = this.onItemClick.bind(this);
  };

  onItemClick () {
    console.log('Test');
  }

  render() {
    const home = React.createElement('li', {className: 'navbar-item', id: 'home'}, 'Home');
    const contact = React.createElement('li', {className: 'navbar-item', id: 'about'}, 'Contact');
    const about = React.createElement('li', {className: 'navbar-item', id: 'contact', onClick: this.onItemClick()}, 'About');

    return React.createElement('ul', {className: 'navbar'}, about, contact, home);
  }

}

var testbar = new Navbar;
ReactDOM.render(
  React.createElement(testbar.render(), null, null),
  document.getElementById('navbar')
);

Any tips on getting the onclick function to work?

2 Answers

You just have to pass your class to ReactDOM.render method and let it handle the instance generation and rendering.

Also, you were calling your onItemClick method instead of passing it to the onClick event listener.

// Navbar Component
class Navbar extends React.Component {

  constructor() {
    super();
    this.onItemClick = this.onItemClick.bind(this);
  };

  onItemClick() {
    console.log('Test');
  }

  render() {
    const home = React.createElement('li', {
      className: 'navbar-item',
      id: 'home'
    }, 'Home');
    const contact = React.createElement('li', {
      className: 'navbar-item',
      id: 'about'
    }, 'Contact');
    const about = React.createElement('li', {
      className: 'navbar-item',
      id: 'contact',
      onClick: this.onItemClick
    }, 'About');

    return React.createElement('ul', {
      className: 'navbar'
    }, about, contact, home);
  }

}

ReactDOM.render(
  React.createElement(Navbar, null, null),
  document.getElementById('navbar')
);
<div id="navbar"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

Change

const about = React.createElement('li', {className: 'navbar-item', id: 'contact', onClick: this.onItemClick()}, 'About');

to

const about = React.createElement('li', {className: 'navbar-item', id: 'contact', onClick: this.onItemClick}, 'About');

Hope it helps

Related