how to use react in Codepen with es6

JessieZhou picture JessieZhou · Feb 14, 2017 · Viewed 11k times · Source

http://codepen.io/JessieZhou/pen/VPgMdP ,Here is a demo using React in CodePen, but the browser gives an error "Uncaught ReferenceError: Component is not defined". However, if I insert a line "import {Component} from 'react'" in the first line, the error will be "Uncaught ReferenceError: require is not defined". Is it possible that the usage of 'class' causes this problem?

Here is my code:

//import {Component} from 'react'
class MyInput extends Component{
   constructor(props){
     super(props);
     this.handleChange = this.handleChange.bind(this);
   }

   handleChange(e){
     this.props.update(e.target.value);
   }

   render(){
     return <input onChange={this.handleChange} type="text"/>
   }
}
ReactDOM.render(MyInput, document.getElementById('myinput'));

Here is my javascript settings in CodePen: javascript settings in codepen

Answer

Mayank Shukla picture Mayank Shukla · Feb 14, 2017

Reason is Component is part of React, to access that you need to use React.Component, if you directly want to use Component, then first import it from react, like this:

import {Component} from 'react';

Use this:

class MyInput extends React.Component{
    constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
    console.log('e', e.target.vaule);
  }
  render(){
    return <input onChange={this.handleChange} type="text"/>
  }
}
ReactDOM.render(<MyInput/>, document.getElementById('myinput'));

Check codepen