React and Express not working? - javascript

I'm fairly new to Node.js, react, and Express. I'm trying to make a basic application and it seems like I can't initialize express.
When I do npm start I get this in the terminal
./node_modules/express/lib/view.js
81:13-25 Critical dependency: the request of a dependency is an expression
My package.json looks like
{
"name": "matchplay",
"version": "0.1.0",
"private": true,
"dependencies": {
"express": "^4.16.2",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.0.17"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {}
}
and my index.js looks like
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {AppTitle, LoginForm} from './App';
import registerServiceWorker from './registerServiceWorker';
const express = require('express')
const app = express();
const element = (<div>
<AppTitle/>
<LoginForm/>
</div>);
ReactDOM.render(element, document.getElementById('root'));
registerServiceWorker();
When I go to my localhost:3000 the following error is given to me;
TypeError: Cannot read property 'prototype' of undefined
./node_modules/express/lib/request.js
node_modules/express/lib/request.js:31
Can someone point me in the right direction?

you should divide the server (express app) and client (react web) to separated folders and implement them in each folder individualy

If you are planning on serving your react app with express your code won't do, you are giving your client express which will basically allow them to host their own server?
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {AppTitle, LoginForm} from './App';
import registerServiceWorker from './registerServiceWorker';
const express = require('express') //<--- Here
const app = express(); //<--- and here
//These should not be here
const element = (<div>
<AppTitle/>
<LoginForm/>
</div>);
ReactDOM.render(element, document.getElementById('root'));
registerServiceWorker();
If you want to serve your react build using an express server it should be a separate project, or at-least a meta project where the react app builds into your express app's public directory.

Related

React : "Module not found " when importing component from a local project

In a React ProjectA, I want to import and use a ./src/components/package/MyComponent from React projectB.
ProjectB is successfully compiled, without any errors. In ProjectB index.js file I have exported the component
import ReactDOM from "react-dom";
import App from './App';
import "./app.css";
export { default as MyComponent } from './components/package/MyComponent';
ReactDOM.render(<App />, document.getElementById("root"));
In PojectA package.json file, I have imported the projectB module
"dependencies": {
"#somescope/projectB": "file:../projectB",
"axios": "^0.19.2",
"date-fns": "^2.10.0",
"interweave": "^12.5.0",
"lodash": "^4.17.15",
"material-icons": "^0.3.1",
"react": "^16.8.0",
"react-dom": "^16.8.0",
"react-grid-system": "^6.2.4",
"react-intersection-observer": "^8.26.2",
"react-scripts": "3.2.0"
},
I have run "npm install", "npm install #somescope/projectB" and "npm install --save ../projectB", to install the projectB module into projectA. After running these commands I can see projectB is present under projectA/node_modules folder.
But when I try to import and use the MyComponent :
import {MyComponent} from "#somescope/projectB";
and run "npm start" command it is giving below error in console :
Module not found: Can't resolve '#somescope/projectB'
Can anyone please help, what am I doing wrong and how to resolve this error?
export { default as MyComponent } from './components/package/MyComponent';
That line seems like you made a default export. If that is the case then to import that component you would need to do this:
import MyComponent from "#somescope/projectB";
I removed the {} since it might be a default export.

How to client-side-routing with create-react-app

tl;dr: What changes do I need to make to the npx create-react-app environment to enable client-side routing with react-router?
EDIT: Answered my own question, do not use href to link to within your app, use react-router-dom 'Link'.
In more detail..
I have followed Andrew Mead's React tutorial and all went well.
His setup utilised webpack with the following inserted to the webpack.config.js file..
devServer:{
contentBase:path.resolve(__dirname, 'public'),
historyApiFallback: true
}
..where historyApiFallback: true meant his dev-server utilised client-side routing vs server-side.
Now that I finished the bulk of the tutorial I decided to create my own app using npx create-react-app.
Everything is working fine, but the routing is not client-side and there is no webpack.config.js file.
I understand CSR works by serving index.html only and manipulating the DOM in the background.
The documentation states one way to make this work is to import 'express' which isn't part of the create-react-app initial environment, and include some code using the variable app. However, I don't actually know where this file lives / should live / where to important/edit etc, or whether express is actually required and perhaps there's a way to "natively" do this without adding another module to my react package.
Here are the relevant script snippets for clarity in case I have done something wrong.
Thanks in advance.
Paul.
index.js
// react imports
import React from 'react';
import ReactDOM from 'react-dom';
// materialize imports
import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';
import './styles/customcss.css';
// redux imports
import store from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';
// component imports
import AppRouter from './app/router';
// app render
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<AppRouter />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
./app/router/
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import AppMainPage from "../pages/portalPage";
import ConnectedAccountPage from "../pages/accountPage";
import ConnectedPostPage from "../pages/postPage";
import { SiteWideNavBar } from "../components/sitewide/navbar";
import { SiteWideFooter } from "../components/sitewide/footer";
const AppRouter = () => (
<BrowserRouter>
<div>
<SiteWideNavBar />
<Switch>
<Route path="/" exact={true} component={AppMainPage} />
<Route path="/account" exact={true} component={ConnectedAccountPage} />
<Route path="/post" exact={true} component={ConnectedPostPage} />
</Switch>
<SiteWideFooter />
</div>
</BrowserRouter>
);
export default AppRouter;
EDIT: package.json if relevant
{
"name": "myproject",
"version": "0.1.0",
"private": true,
"dependencies": {
"#reduxjs/toolkit": "^1.5.0",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"materialize-css": "^1.0.0-rc.2",
"moment": "^2.29.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-forms-materialize-css": "^1.0.1",
"react-google-maps": "^9.4.5",
"react-icons": "^4.1.0",
"react-materialize": "^3.9.6",
"react-redux": "^7.2.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"uuid": "^8.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Everything was configured correctly, the issue was I was using NavItem with href="/" etc from react-materialize in my navbar and not Linkfrom from react-router-dom.
If you are getting this issue: You should be using Link from r-r-d and for any redirects also use props.history.push('/'). Whilst this part wasn't relevant to my issue, if you are here you might be experiencing the same issue by trying to redirect using something other than a prop.history.push() method.

How to get ReactJs to work with FullCalendar

I'm having a hard time getting FullCalendar to work properly with ReactJs. The calendar shows up but it does not look correct and passing in arguments to $("#calendar").fullCalendar() does NOT do anything as you can see from the image below. (should have day 6 - 8 highlighted green)
So I started out with create-react-app that just jump starts the project for me with all of the needed dependencies such as Babel and what not.
Then made 2 very simple React classes like so:
import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';
import 'moment/min/moment.min.js';
import 'fullcalendar/dist/fullcalendar.css';
import 'fullcalendar/dist/fullcalendar.print.min.css';
import 'fullcalendar/dist/fullcalendar.js';
class Calendar extends Component {
componentDidMount(){
const { calendar } = this.refs;
$(calendar).fullCalendar({events: this.props.events});
}
render() {
return (
<div ref='calendar'></div>
);
}
}
class App extends Component {
render() {
let events = [
{
start: '2017-01-06',
end: '2017-01-08',
rendering: 'background',
color: '#00FF00'
},
]
return (
<div className="App">
<Calendar events={events} />
</div>
);
}
}
export default App;
I have no clue where the mistake is so I did what anyone would do and google around to see if someone has already ran into this issue and I came across this short video tutorial on exactly this and still does not work properly.
Here is my package.json file:
{
"name": "cal-test",
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-scripts": "0.8.5"
},
"dependencies": {
"fullcalendar": "^3.1.0",
"jquery": "^3.1.1",
"moment": "^2.17.1",
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Iv'e tried everything I could think of and still no luck, help is greatly appreciated.
Thank you so much!
creator of that video here. I'd remove that call to import 'fullcalendar/dist/fullcalendar.print.min.css';, because it's most likely overriding the CSS of the stylesheet before it.
The latest version v4 of Fullcalendar.io now has ReactJS documentation. I would use the React Components recommended by the FullCalendar creators:
https://fullcalendar.io/docs/react
FullCalendar seamlessly integrates with the React JavaScript
framework. It provides a component that exactly matches the
functionality of FullCalendar’s standard API.
This component is built and maintained by Josh Ruff of Sardius Media
in partnership with the maintainers of FullCalendar. It is the
official React connector, released under an MIT license, the same
license the standard version of FullCalendar uses.
Fullcalendar now provides a React wrapper, and it works nicely with Create React App. Instead of importing CSS via Sass, you can import them directly like so:
import "#fullcalendar/core/main.css"
import "#fullcalendar/daygrid/main.css"

React js tomcat, Uncaught SyntaxError: Unexpected token import

I am new to react js, i am trying to create react js based simple page using export and import functionality. Below is the description
App.jsx
import React from '../build/react'
export default class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
main.jsx
import {ReactDOM} from '../build/react-dom'
import {App} from 'App'
ReactDOM.render(<App />, document.getElementById('app'));
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="build/browser.min.js"></script>
<script src="custom/main.jsx"></script>
</head>
</html>
I have deployed it on tomcat, when i am trying to access "test.html" from browser it is giving me
Uncaught SyntaxError: Unexpected token import at main.jsx : 1
Please help me, whether i have missed anything in this.
I had a similar problem. I did all that I could to solve it but to no avail. I deleted node_module from C: and issued npm install to reinstall node_module but still no solution.
I replaced my package.json with
{
"name": "react-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.16.2",
"express": "^4.16.2",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router-dom": "^4.1.1",
"react-scripts": "0.9.5"
},
"devDependencies": {},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
and replaced my index.js with
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
I later made changes to them to suit my app's requirements. It worked perfectly - I can't explain how it happened.

Uncaught ReferenceError: React is not defined

I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
But I can access the React object in browser console
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined
Can anyone suggest me on how to resolve this?
[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:
var Comment = React.createClass({
render: function () {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
var ready = function () {
React.renderComponent(
<Comment author="Richard" comment="This is a comment "/>,
document.getElementById('comments')
);
};
$(document).ready(ready);
And this is my index.html.erb:
<div id="comments"></div>
If you are using Babel and React 17, you might need to add "runtime": "automatic" to Babel config.
In .babelrc config file this would be:
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", {"runtime": "automatic"}]
]
}
I got this error because I was using
import ReactDOM from 'react-dom'
without importing react, once I changed it to below:
import React from 'react';
import ReactDOM from 'react-dom';
The error was solved :)
I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:
externals: {
'react': 'React'
},
This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).
If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.
Add to webpack.config.js:
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin
Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.
P.S
Possible solutions.
If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
Make sure you have the line import React from 'react';
Try to add:
import React from 'react'
import { render } from 'react-dom'
window.React = React
before the render() function.
This sometimes prevents error to pop-up returning:
React is not defined
Adding React to the window will solve these problems.
Adding to Santosh :
You can load React by
import React from 'react'
I know this question is answered. But since what worked for me isn't exactly in the answers, I'll add it here in the hopes that it will be useful for someone else.
My index.js file looked like this when I was getting Uncaught ReferenceError: React is not defined.
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Adding import React from 'react'; at the top of the file fixed it.
Now my index.js looks like this and I don't get any error on the console.
import React from 'react';
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Please note I made no change in webpack.config.js or anywhere else to make this work.
import React, { Component, PropTypes } from 'react';
This may also work!
If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".
I was facing the same issue.
I resolved it by importing React and ReactDOM like as follows:
import React from 'react';
import ReactDOM from 'react-dom';
I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.
I got this error because I used:
import React from 'react';
while working with React, Typescript and Parcel
Changing it to:
import * as React from 'react';
Solved the problem as suggested by https://github.com/parcel-bundler/parcel/issues/1199#issuecomment-381817548
Sometimes the order of import can cause this error, if after you have followed all the steps above and still finds it hard on you, try making sure the react import comes first.
import React from 'react'
import { render } from 'react-dom'
before any other important you need to make.
The displayed error
after that import react
Finally import react-dom
if error is react is not define,please add ==>import React from 'react';
if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';
To whom using CRA and ended up to this question, can use customize-cra and react-app-rewired packages to override babel presets in CRA.
To do this, create a config-overrides.js in the root and paste this code snippet in it.
const { override, addBabelPreset } = require('customize-cra');
module.exports = override(
addBabelPreset('#emotion/babel-preset-css-prop'),
addBabelPreset([
'#babel/preset-react',
{
runtime: 'automatic',
importSource: '#emotion/react',
},
]),
);
And update scripts in package.json with the ones below.
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
I got this because I wrote
import react from 'react'
instead of
import React from 'react'

Categories