Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React ES6: you may have forgotten to define `render`

I stuck for a while ,and do not know where is wrong ,Please help me

Here is the error message:

Warning: App(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.
Uncaught TypeError: inst.render is not a function

here is my code :

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

console.log('Start')

export class App extends React.Component{
  constructor(props) {
     super(props);
     console.log('getInitialState');
     return { status:true }
  }
  toggleState(){
    this.setState({status: !this.state.status})
  }
  render() {
    console.log('render');
        return (
           <div>
              <h1 onClick={this.toggleState}>Hello</h1>
           </div>
        );
     }

} 

ReactDOM.render(<App name='Vipul' />,document.getElementById('app'));
like image 345
user2492364 Avatar asked Apr 26 '16 09:04

user2492364


1 Answers

Remove return from constructor, and state must be as a property like so

constructor(props) {
  super(props);
  this.state = { status: true };
}

Example

Look at these two examples

function App() {
   return { status: true }
}
App.prototype.render = function() {};
console.log(typeof new App().render);

function App() {
  this.state = { status: true };
}
App.prototype.render = function() {};

console.log(typeof new App().render);

as you can see in console you get in first example undefined it is because constructor App returns new custom object, and in second you get right result;

like image 87
Oleksandr T. Avatar answered Oct 26 '22 16:10

Oleksandr T.