1

I am new to ReactJS and am trying to update the page when the user clicks on the navigation bar, however the page does not update. I am getting the error:

Warning: Can't call setState on a component that is not yet mounted.

Currently the navbar looks like:

// Navbar Component
class Navbar extends React.Component {

  constructor(){
    super();
    this.state = {page: 'home'};
    this.onHomeClick = this.onHomeClick.bind(this);
    this.onAboutClick = this.onAboutClick.bind(this);
  }

  onHomeClick(){

    this.setState({page: 'home'});

  }

  onAboutClick(){

    this.setState({page: 'about'});

  }

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

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

    return navbar;
  }

}

And the final application renders the final result as follows:

// App
class App extends React.Component{

  constructor(props){
    super(props);
  }

  render() {
    var navbar = new Navbar;
    var header = new Header;
    var slideshow = new Slideshow;
    var aboutMe = new AboutMe;

    if(navbar.state.page == 'home'){
      return React.createElement('div', {className: 'main-page'}, navbar.render(), header.render(), slideshow.render());
    } else if (navbar.state.page == 'about'){
      return React.createElement('div', {className: 'about-page'}, navbar.render(), header.render(), aboutMe.render());
    }
  }
}


// Render Application components
ReactDOM.render(
  React.createElement(App, null, null),
  document.getElementById('root')
);

Any ideas on handling the onclick events gracefully?

  • 1
    If you are new to Reactjs and you happen to follow any of the tutorial, then you are following outdated material which was probably from 2015. – Rikin Oct 12 '19 at 12:56

1 Answers1

0

Okay the error you are getting is because you are not calling the constructor for Navbar component.

change this

var navbar = new Navbar;

to

var navbar = new Navbar(); // call constructor

Change your other components constructor as well

Hope it helps

ibtsam
  • 1,620
  • 1
  • 10
  • 10
  • For the `new` operator, parenthesis can be [omitted](https://stackoverflow.com/questions/3034941/can-we-omit-parentheses-when-creating-an-object-using-the-new-operator) if there are no arguments in the function call – Hamza El Aoutar Oct 12 '19 at 13:53