how to use react in Codepen with es6
Instead of using import, use destructuring assignments to get React.Component. After adding react to codepen through js settings, it executes the script which will make React available on global scope, window.
const {Component} = React;
class MyInput extends Component{
//Component code
}
I noticed that process.env.NODE_ENV
is undefined in ReactDOM
16.2 js file, if you import the CDN from Quick-add.
The solution is to use the development react and ReactDOM modules from unpkg.com:
//unpkg.com/react/umd/react.development.js
//unpkg.com/react-dom/umd/react-dom.development.js
There is the example works on React 16.2: CodePen
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
Component is a subclass of react. So either you import it or use React.Component
During render you have to use jsx
MyInput
wont work. <MyInput/>
will work
class MyInput extends React.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'));