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.
Related
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.
Hello I just started using styled-components on my project.
My working environment is:
1) npm version 6.12
2) Node.js version 12.13
3) VS Code
After installing styled-components from official documentation:
sudo npm install --save styled-components
my project does not compile anymore throwing the following error:
Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
object. You likely forgot to export your component from the file it's
defined in, or you might have mixed up default and named imports.
Check the render method of Home.
What I have done so far:
1) As advised by the debugger I double-checked my Home page and tried to see if I forgot to import the component. However it is correctly imported but still does not work.
2) Always as advised by the debugger I checked if there was a invalid type element. However I think the syntax is correct. To be sure about that I consulted the official documentation on how to correctly reference these types of components. Unfortunately it didn't work too.
3) After more research I came across this useful post. It seems that it could be due to a not precise reference to the include. However, my project correctly worked/compiled/built until I installed styled-components. All the import/export I did in the same way.
I am providing the following snippets of code where I have the error:
StyledHero.js
import styled from "styled-components"
const SimpleButton = styled.button`
color:red;
background:green;
`;
export default SimpleButton;
Home.js
import React from 'react'
import Hero from "../components/Hero"
import Banner from "../components/Banner"
import {Link} from "react-router-dom"
import Services from "../components/Services"
import FeaturedVessel from "../components/FeaturedVessels"
import Button from "../components/StyledHero"
export default function Home () {
return (
<>
<Hero hero="defaultHero">
<Banner title="Vessels" subtitle="Currently Tracked Vessels">
<Link to="/vessels" className="btn-primary">
Vessels
</Link>
</Banner>
</Hero>
<Services />
<FeaturedVessel />
<Button>hello</Button>
</>
);
}
Additional option I tried:
As a final note to try to solve the problem I thought that the component I created using styled-components is supposed to be exported with the same name, so I also tried to export it with the exact name of the component create inside StyledHero.js:
StyledHero.js
import styled from "styled-components"
const SimpleButton = styled.button`
color:red;
background:green;
`;
export default SimpleButton;
Home.js
import React from 'react'
import Hero from "../components/Hero"
import Banner from "../components/Banner"
import {Link} from "react-router-dom"
import Services from "../components/Services"
import FeaturedVessel from "../components/FeaturedVessels"
import SimpleButton from "../components/StyledHero"
export default function Home () {
return (
<>
<Hero hero="defaultHero">
<Banner title="Vessels" subtitle="Currently Tracked Vessels">
<Link to="/vessels" className="btn-primary">
Vessels
</Link>
</Banner>
</Hero>
<Services />
<FeaturedVessel />
<SimpleButton>hello</SimpleButton>
</>
);
}
If could be useful below my package.json:
{
"name": "my-project",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-icons": "^3.8.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.0",
"styled-components": "^5.0.0"
},
"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"
]
}
}
Can someone point me in the right direction and understand what is the problem?
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.
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"
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.