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
The codepen provide you an online platform to create react, HTML, CSS, JavaScript project. Codepen also has another advantage that you will easily upload your code to GitHub and share your code with anybody without any difficulty.
You can import React (any pretty much any other npm package) from Skypack like this: import React from "https://cdn.skypack.dev/[email protected]"; CodePen will help you fix imports like that automatically. You'll see an icon like this come up, which you click to open and are offered a button to click to fix the issue.
First go to the Pen you are interested in forking. Then click on the fork button located at the bottom right hand corner. Once you fork the Pen, then it will create a copy for your CodePen account. Make sure to hit the save button and you can start modifying the code from there.
Babel is essentially a preprocessor for JavaScript.
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
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With