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.
Related
I'm trying to add the scroll function in script tags to this header component in Gatsby. I know it could work in html and not in react, but what is the right way to do it? Thanks!
import React from 'react'
import Link from 'gatsby-link'
import './header.css'
const Header = () => (
<div className='Header'>
<div className='HeaderGroup'>
<Link to='/'><img src={require('../img/logo_nav.png')} width='60' /></Link>
<Link to='/index'>Selected Works</Link>
<Link to='/uber'>Uber Thoughts</Link>
<Link to='/awards'>Awards</Link>
<Link to='/about'>About</Link>
</div>
</div>
)
export default Header
<script>
$(window).scroll(function () {
if ($(window).scrollTop() > 10) {
$('.Header').addClass('floatingHeader');
} else {
$('.Header').removeClass('floatingHeader');
}
}
</script>
If you want scripts to load before the DOM is ready you can add your scripts inside html.js file.
From the Gatsby docs:
Gatsby uses a React component to server render the and other
parts of the HTML outside of the core Gatsby application.
Read more about it here.
In your case, what you can do is to write your script inside the componentDidMount react lifecycle method, because you need access to the DOM (as you're using jQuery there) you need to run the script after the body has been loaded, so placing your script in the <head> won't work, you need to add it inside the componentDidMount method by first making your component a class component to get access to the react lifecycle methods.
import React from 'react'
import Link from 'gatsby-link'
import $ from 'jquery'
import './header.css'
class Header extends React.Component {
componentDidMount () {
$(window).scroll(function () {
if ($(window).scrollTop() > 10) {
$('.Header').addClass('floatingHeader');
} else {
$('.Header').removeClass('floatingHeader');
}
})
}
render () {
return (
<div className='Header'>
<div className='HeaderGroup'>
<Link to='/'><img src={require('../img/logo_nav.png')} width='60' /></Link>
<Link to='/index'>Selected Works</Link>
<Link to='/uber'>Uber Thoughts</Link>
<Link to='/awards'>Awards</Link>
<Link to='/about'>About</Link>
</div>
</div>
)
}
}
export default Header
You can also use a Gatsby layout template like the gatsby-starter-blog project and put your script at the bottom of the {children} call as a <script>Your script</script> and it will be available in all your pages, same as using the html.js file but since you need access to the DOM you need to put it inside the body for your script to work (more info about Gatsby layouts here).
Can you please take a look at this demo and let me know why I am not able to toggle .green class for #root using onClick in react js?
function toggler(e){
var x = document.getElementById("root");
x.classList.toggle('green');
}
const Button = ({ styleClass, onClick, text }) => {
return (
<button
type="button"
onClick={e => onClick(e)}
className={`btn ${styleClass}`}
>
{text}
</button>
);
};
ReactDOM.render(
<div>
<Button styleClass="btn-primary" text='Primary Button' onClick={toggler} />
</div>
, window.root);
#root{
height:300px;
width:300px;
background:khaki;
}
.green{
background:green;
}
<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>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="root"></div>
You should not touch the DOM directly when you're writing React components. React can help you manage your class name with state.
Do something like this:
import React, { Component } from 'react';
export default class Button extends Component {
constructor(props) {
super(props);
this.state = {
buttonStyleClass: 'bar'
}
}
toggler = (e) => {
this.setState({
buttonStyleClass: 'foo'
})
}
render() {
return (
<div
className={this.state.buttonStyleClass}
onClick={this.toggler}
>
Click me
</div>
);
}
}
The problem here is that id-selectors have higher priority over class-selectors in css. Since you have defined the base color with #root, you can't toggle it with just .green.
Many solutions here, but one of them could be #root.green, adding !important or selecting your root otherwise.
That being said, you should not mutate the DOM directly when using React. It voids one of its biggest advantages. See mxdi9i7's answer for more info.
I am learning React and following integrating other Libraries chapter and tried the same they have suggested but getting below error
TypeError: this.$el.chosen is not a function
Chosen.componentDidMount
src/App.js:18
componentDidMount() {
this.$el = $(this.el);
> this.$el.chosen();
}
react website provides example codepen where they have added the jquery and chosen plugin js in dependencies and I have added jquery and chosen library js file in index.html and also added jquery using npm install jquery --save so that it can be imported in App.js
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.min.js"></script>
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
App.js
import React, { Component } from 'react';
import $ from 'jquery';
class Chosen extends Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();
}
componentWillUnmount() {
this.$el.chosen('destroy');
}
render() {
return (
<div >
<select className="Chosen-select" ref={el => this.el = el}>
{this.props.children}
</select>
</div>
);
}
}
function Example() {
return (
<Chosen >
<option >vanila</option>
<option >strawberry</option>
<option >chocolate</option>
</Chosen>
);
}
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<section>
<Example/>
</section>
</div>
);
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
Why I am getting this error and how to fix it?
Got it to work by following these steps (after creating a project using create-react-app)
npm install jquery --save
npm install chosen-js --save
Add this in line #1 of node_modules/chosen-js/chosen.jquery.js
import jQuery from 'jquery'
As per this answer
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import $ from 'jquery'
import "chosen-js/chosen.css";
import "chosen-js/chosen.jquery.js";
class Chosen extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();
this.handleChange = this.handleChange.bind(this);
this.$el.on('change', this.handleChange);
}
componentDidUnmount() {
this.$el.off('change', this.handleChange);
this.$el.chosen('destroy');
}
handleChange(e) {
this.props.onChange(e.target.value);
}
render() {
return (
<div>
<select className="Chosen-select" style={{width: "200px"}} ref={el => this.el = el}>
{this.props.children}
</select>
</div>
);
}
}
function Example() {
return (
<Chosen className="chosen-container chosen-container-single" onChange={value => console.log(value)}>
<option>vanilla</option>
<option>chocolate</option>
<option>strawberry</option>
</Chosen>
);
}
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
<Example/>
</p>
</div>
);
}
}
export default App;
I have also face the same issue while reading the documentation. But instead of updating the "node_modules/chosen-js/chosen.jquery.js" file, I prefer to Use the ProvidePlugin to inject implicit globals in webpack.config.js
But when we create an application using create-react-app we didn't find the webpack.config.js file.
You will need to eject the react application. But you should first read from the following links before ejecting the application(If you’re a power user and you aren’t happy with the default configuration).
Links:-
https://github.com/satendra02/react-chrome-extension/wiki/What-happens-when-you-eject-Create-React-App
https://medium.com/curated-by-versett/dont-eject-your-create-react-app-b123c5247741
You will need to run the following command to eject the react application as this command will remove the single build dependency from your project and also copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc.) into your project as dependencies in package.json
npm run eject
Install the dependencies
npm install jquery chosen-js --save
Now edit your webpack.config.js file and update the config object as follow
return {
...
module: {
...
},
plugins: [
...
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
]
...
}
Chosen.js
import React from 'react';
import $ from "jquery";
import "chosen-js/chosen.css";
import "chosen-js/chosen.jquery.js";
class Chosen extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();
this.handleChange = this.handleChange.bind(this);
this.$el.on("change", this.handleChange);
}
componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
this.$el.trigger("chosen:updated");
}
}
componentWillUnmount() {
this.$el.off("change", this.handleChange);
this.$el.chosen("destroy");
}
handleChange(e) {
this.props.onChange(e.target.value);
}
render() {
return (
<div>
<select className="Chosen-select" ref={(el) => (this.el = el)}>
{this.props.children}
</select>
</div>
);
}
}
It seems like a issue related with dependency.
I notice that you include JQuery and its chosen plugin with CDN which means it is declared globally. But in third line of App.js you import $ from 'jquery'; which may introduce JQuery locally. In my experience, React will refer $ to local JQuery which is not with the plugin.
I suggest that you could try comment out import $ from 'jquery' and try again.
Good luck!
Use
window.$("#infomodal").modal("hide");
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
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>