ReactJs, the SyntaxError with `static defaultProps` - reactjs

I use the React to write this demo. I use the Webpack to build this demo.When I start this demo, the error will show me.
ERROR in ./src/app.js
Module build failed: SyntaxError: Unexpected token (8:24)
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class Button extends Component {
constructor(props){
super(props);
}
static defaultProps = {
color:'blue',
text: 'Confirm',
}
render (){
return (
<button className={'btn btn-${color}'}>
<em>{text}</em>
<p>This is a button.</p>
</button>
);
}
}
ReactDOM.render(<Button />, document.getElementById('app'));
I read this demo from a book. Due to the book is probably print the wrong code. So I ask this question now.
The error show static defaultProps = { is not right. The book is also written with this form. Do you know the right code?

The terminal executes npm install --save-dev babel-preset-stage-0 in the current directory.
Add stage-0 to the current directory * .babelrc * file
{
"Presets": ["react", "es2015", "stage-0"],
}}

It could be some error in your webpack setup. Otherwise defaultProps is defined correctly as it should be.
One more thing to access the props you need to use this.props.propName
Check the below code -
class Button extends React.Component {
constructor(props){
super(props);
}
static defaultProps = {
color:'blue',
text: 'Confirm'
}
render (){
return (
<button className={'btn btn-${this.props.color}'}>
<em>{this.props.text}</em>
<p>This is a button.</p>
</button>
);
}
}
ReactDOM.render(<Button />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Related

How do I import react-modal into existing application?

I've been slowly trying to migrate some pieces of an existing, large php/jquery project to use ReactJS, especially using some reusable components. ReactJS has been working well for me, but today I tried to import a library using npm, which is completely new to me.
After running npm install react-modal I see that node_modules\react-modal (along with several other folders) were created. So far, so good.
However, I cannot seem to include that component into my project. If I try import ReactModal from 'react-modal'; at the top of my component's .js file, I get: Uncaught ReferenceError: require is not defined. I get errors thrown if I try to include the node_modules\react-modal\lib\components\Modal.js file directly, which I realize is probably the wrong approach but I'm grasping at straws here. I suspect I'm missing something basic, but I just can't seem to figure this one out. Does anyone have any ideas?
Edit: here is how I include React into my project currently:
<!-- Load React. -->
{if $env=="prod"}
<script src="https://unpkg.com/react#16/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js" crossorigin></script>
{* tabs support *}
<script src="https://unpkg.com/prop-types/prop-types.js"></script>
<script src="https://unpkg.com/react-tabs#3/dist/react-tabs.production.min.js"></script>
<link href="https://unpkg.com/react-tabs#3/style/react-tabs.css" rel="stylesheet">
{else}
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
{* tabs support *}
<script src="https://unpkg.com/prop-types/prop-types.js"></script>
<script src="https://unpkg.com/react-tabs#3/dist/react-tabs.development.js"></script>
<link href="https://unpkg.com/react-tabs#3/style/react-tabs.css" rel="stylesheet">
{/if}
{* Babel support *}
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
This is the full component (contents of the matchSelector.js file):
import Modal from 'react-modal';
/**
* Select a match with hooks to return the proper match info to the instantiator
*/
class MatchSelector extends React.Component {
/**
* Class Constructor
*
* props expected:
* className - (optional) use if you want to style the picker button/icon differently. Note that
* if given, all standard classes will be overrided.
*
* type - (optional) can be "text", "icon", "both". Default is "both".
*
* text - (optional) if type is "text" or "both", the text to use on the button. Default is "Select Match"
*
*/
constructor(props) {
super(props); // let Dad know what's up
this.state = {showDialog:false}
this.handleClick = this.handleClick.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleClick(event) {
event.preventDefault();
this.setState({showDialog:true});
}
handleClose() {
this.setState({showDialog:false});
}
render() {
const defaultClassName = "ui-state-default ui-corner-all ui-button compressed";
let className = (odcmp.empty(this.props.className)?defaultClassName:this.props.className);
return (
<React.Fragment>
<button
className={className}
onClick={this.handleClick}>
{this.buttonContent()}
</button>
<MatchSearchDialog
show={this.state.showDialog} />
</React.Fragment>
);
}
buttonContent() {
var text = (odcmp.empty(this.props.text)?"Select Match":this.props.text);
if (odcmp.empty(this.props.type) || (this.props.type.toLowerCase()=="both")) {
return (
<span><span className="ui-icon ui-icon-search inline"></span>{text}</span>
);
} else if (this.props.type.toLowerCase()=="icon") {
return (
<span className="ui-icon ui-icon-search inline"></span>
);
} else {
return text;
}
}
}
class MatchSearchDialog extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<ReactModal isOpen={false}><div>hi</div></ReactModal>
);
}
}
The doc of the npm package state that to import your modal, you need to write:
import Modal from 'react-modal';
It's not import ReactModal from 'react-modal'; as you tried (ReactModal => Modal).
With this eveything works fine for me as you can see on this repro on Stackblitz. Here is the code :
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import Modal from 'react-modal';
import "./style.css";
Modal.setAppElement('#root');
const App = () => {
const [modalIsOpen,setIsOpen] = React.useState(false);
const openModal = () => {
setIsOpen(true);
}
const closeModal = () => {
setIsOpen(false);
}
return (
<div>
<p>Start editing to see some magic happen :)</p>
<button onClick={openModal}>Open Modal</button>
<Modal
isOpen={modalIsOpen}
contentLabel="Example Modal"
>
<div>Wow nice modal !</div>
<button onClick={closeModal}>close</button>
</Modal>
</div>
);
};
render(<App />, document.getElementById("root"));
In case anyone runs into this, I wanted to add my resolution.
I was trying to run a bare bones REACTJS project without webpack. react-modal depends on webpack (as does, I'm sure, many React components). As I'm trying to stay light and agile, I removed the react-modal module and "rolled my own" modal dialog.
FYI, the clue is the "require not defined" error in the console - indicating a non-browser (node.js) function was hit. It was expecting to compile (webpack) into a separate js file using the node.js terminology.

React - Coding Error

I am following tutorial from: https://www.youtube.com/watch?v=OzqR10jG1pg
Using Code Editor: https://stackblitz.com
Coding error reads:
Error in index.js (36:10)
'}' expected.
Error line reads:
render: function () {
How do I get this code to work?
Here is my Code:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
render(<App />, document.getElementById('root'));
<div id="example"></div>
<script type="text/babel">
var Bacon = React.createClass({
render: function () {
return (<h3>This is a simple component!</h3>);
}
});
ReactDOM.render(<Bacon />, document.getElementById('example'));
</script>
It looks like you are putting HTML code into your javascript (index.js) file. You should have a separate HTML file for that.
I can see you are trying to render two different apps.
First, when you use ReactDOM.render(<Bacon />, document.getElementById('example')); you're telling React to render the component Bacon in the HTML element that has an ID attribute 'example'.
Then, with render(<App />, document.getElementById('root'));, React will look for an element that has an ID attribute 'root'.
So you should have both elements in your HTML file, like the snippet below.
// index.js
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<div>{this.state.name}</div>
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<!-- index.html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="example"></div>
<div id="root"></div>
<script type="text/babel">
var Bacon = React.createClass({
render: function () {
return (<h3>This is a simple component!</h3>);
}
});
ReactDOM.render(<Bacon />, document.getElementById('example'));
</script>

Importing a JSX file in another JSX file

I'm a very beginner in React. I created a general React Component in a JSX file and then I intend to import it in another JSX file. However, when I import the following error is returned ReferenceError: require is not defined.
This is my general object:
class Footer extends React.Component{
render(){
return (
<div>Footer</div>
);
}
}
export default Footer;
And this is the other JSX file:
import Footer from './generalPageFooter.jsx';
const contentNode = document.getElementById('div-content');
class AdminPanel extends React.Component{
render(){
return (
<div>
<h3>Sample Text</h3>
</div>
);
}
}
class AdminPage extends React.Component{
render(){
return (
<div>
<h3>Sample Text</h3>
</div>
);
}
}
ReactDOM.render(<AdminPage />, contentNode);
In the HTML file the code is the following:
<body>
<div id="div-content">
</div>
<script type="text/babel" src="/adminPage.jsx"></script>
</body>
You cannot directly run ES6/JSX on the browser. They need to be transpiled to "pure" JS then browser can understand and execute them.
Take a look on Babel.
P/S: If you are starting with React, I suggest create-react-app from Facebook.

react render doesn't show anything

My react codepen is not showing anything.
JS
class HelloWorld extends React.Component {
render() {
return (<div>Hello World!</div>);
}
}
var app = document.getElementById("mainapp");
React.render(<HelloWorld />, app);
HTML
<div id='mainapp'></div>
I imported React and ReactDOM trough a cdn. And if I type React/ReactDOM in the console it is imported correctly. This code doesn't show any errors yet I see nothing. I tested this on multiple browsers (chrome, firefox, icecat) but still no results... I'm using bable is a preprocessor.
ReactDOM.render not React.render.
class HelloWorld extends React.Component {
render() {
return <div>Hello World!</div>;
}
}
var app = document.getElementById("mainapp");
ReactDOM.render(
<HelloWorld/>,
app
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id='mainapp'></div>
Your component needs to return an element instead of a naked string. Try to modify it to <div>Hello World!</div>
Two things
You need to return a valid react element
Use ReactDOM.render instead of React.render
Snippet
class HelloWorld extends React.Component {
render() {
return <div>"Hello World!"</div>
}
}
var app = document.getElementById("mainapp");
ReactDOM.render(<HelloWorld />, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="mainapp"></div>
Also see this answer on why you should use ReactDOM
react vs react DOM confusion

integrating js code inside react component

I have converted a component that displays chart bar, and it requires this js snippet to run, what is the correct way of integrating it inside my JSX code?
<script>
/** START JS Init "Peity" Bar (Sidebars/With Avatar & Stats) from sidebar-avatar-stats.html **/
$(".bar.peity-bar-primary-avatar-stats").peity("bar", {
fill: ["#2D99DC"],
width: 130,
})
</script>
I have seen this libraries on npm website, but they mostly deal with external scripts not internal
here is my component:
import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div>
"How can I render js code here?"
</div>
);
}
}
You can use refs and componentDidMount callback in order to initialize jquery plugins, like so
class App extends React.Component {
componentDidMount() {
$(this.barChart).peity("bar", {
fill: ["#2D99DC"], width: 130
});
}
render() {
return <div>
<div ref={ (node) => { this.barChart = node } }>
<span class="bar">5,3,9,6,5,9,7,3,5,2</span>
<span class="bar">5,3,2,-1,-3,-2,2,3,5,2</span>
<span class="bar">0,-3,-6,-4,-5,-4,-7,-3,-5,-2</span>
</div>
</div>;
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/peity/3.2.1/jquery.peity.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
You should use componentDidMount lifecycle hook.
Add this to your component code:
componentDidMount() {
$(".bar.peity-bar-primary-avatar-stats").peity("bar", {
fill: ["#2D99DC"],
width: 130,
})
}

Resources