React.js - "Invariant Violation: Element type is invalid: expected a string" Simple Button

- 1 answer

Ad
import React from 'react';

class App extends React.Component {
  constructor(){
    super();
    this.update = this.update.bind(this)
    this.state = {val: 0}
  }
  update(){
    this.setState({val: this.state.val + 1});
  }
  componentWillMount() {
    console.log("Will mount");
  }
  render() {
    return (
      <button onClick={this.update}>
        {this.props.txt} - {this.state.val}
      </button>
    );
  }
  componentDidMount() {
    console.log("mounted");
  }
}

App.defaultProps = {txt: 'button'}

I'm trying to follow a tutorial about React, to create a simple button that has a "txt" value that increases by one every time it's clicked. A separate main.js loads this file like this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('app'));

The error says that the element I'm targeting isn't a string, but 'app' is a string, so I'm not sure why it's not rendering. Any ideas? Here's the index.html file I'm loading:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Lesson 11</title>
</head>
<body>
  <div id="app"></div>
  <script src="index.js"></script>
</body>
</html>

Thanks for any help!

Ad

Answer

Ad

You need export App class component from ./App file

export default class App extends React.Component {

ES6 Modules

Ad
source: stackoverflow.com
Ad