React router page rendering issue - javascript

Learning React right now tried to use react-router for page routing, but because of some reasons I always see the blank page instead of rendered component.
I'm using webpack-dev-server as dev server.
Looking for your help and advices
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="dist/css/app.css">
</head>
<body>
<div id="root"></div>
<script src="dist/js/app.js"></script>
</body>
</html>
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRoute, hashHistory } from "react-router";
import App from './Pages/App';
import Archives from './Pages/Archives';
import Features from './Pages/Features';
import Settings from './Pages/Settings';
const app = document.getElementById('root');
// ReactDOM.render(<Layout/>, app);
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Features}/>
<Route path='archives' component={Archives}/>
<Route path='settings' component={Settings}/>
</Route>
</Router>
, app);
App component
import React from 'react';
import { Link } from 'react-router'
export default class App extends React.Component{
render(){
return (
<div>
<h1>App</h1>
<Link to="/archives">Archives</Link>
<Link to="/settings">Settings</Link>
{this.props.children}
</div>
);
}
}
package.json
{
"name": "Planner",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"history": "^4.6.1",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router": "^4.1.1",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
UPDATED:
Webpack config
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/app.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: "app.js",
publicPath: '/dist/js/'
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};

Related

Using React in only one part of a multi-page application

I already have a multi-page website which currently has two tools built with Node.js, Express, MongoDB, vanilla JS. Each tool has its own web page. I want to add a third tool on my website. This new tool will be built using React.
The main "App" component should have a "Top", "Body" and "Bottom" component. However, when I try to import these components into the App file, the content does not show.
App component:
import React from 'react';
import Top from './Top/Top.js';
import Body from './Body/Body.js';
import Bottom from './Bottom/Bottom.js';
class App extends React.Component {
render() {
return (
<div>
<Top />
<Body />
<Bottom />
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
Top component:
import React from 'react';
class Top extends React.Component {
render() {
return (
<div>
<div>Top goes here</div>
</div>
);
}
}
export default Top;
Body component and Bottom component are similar to Top.
When I import the components into the App, the content does not show. However, if I do not import and write all the components in one file, the content shows.
I would like to separate the components into separate files as shown above for easier readibility and navigation.
Furthermore, when I try to import the components into the main App component, I also get this error in the Chrome web developer console:
How can I separate my components into separate files and import them correctly where needed without errors?
Thanks!
Edit: this is my webpack configuration
const path = require('path');
const autoprefixer = require('autoprefixer');
module.exports = {
entry: './public/js/birdApp/birdApp.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: ''
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: {
localIdentName: "[name]__[local]___[hash:base64:5]",
},
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
autoprefixer({})
]
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=10000&name=img/[name].[ext]'
}
]
}
};
Edit2: my package.json file
"name": "rstools",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "env-cmd -f ./config/dev.env nodemon src/app.js --ext js,hbs,css"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-react-app": "^3.1.2",
"body-parser": "^1.19.0",
"env-cmd": "^10.1.0",
"express": "^4.17.1",
"hbs": "^4.1.1",
"mongodb": "^3.5.7",
"mongoose": "^5.9.11",
"osrs-json-api": "^1.4.1",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"#babel/core": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"autoprefixer": "^9.8.4",
"babel-loader": "^8.1.0",
"css-loader": "^3.6.0",
"html-loader": "^1.1.0",
"html-webpack-plugin": "^4.3.0",
"postcss-loader": "^3.0.0",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-node-externals": "^2.3.0"
}
}

ReactJS code compiled successfully , but not printing on Browser

After a lot of efforts i was able to install and configure ReactJS. After executing "npm start" command, the code was "COMPILED SUCCESSFULLY" and redirected me to the web browser.
But there wasn't any output, ie., the browser was "blank".
Can anyone resolve this?? ( my first post here )
Also check the code that i have used..
index.html file
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = 'index_bundle.js'></script>
</body>
</html>
App.js
import React, { component } from 'react';
class App extends Component {
render(){
return(
<div>
<h1> Hello World</h1>
<p>Hello </p>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app'));
package.json snippet
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
The only issue is the output is not getting displayed on browser..
command prompt
COMMAND PROMPT AFTER "npm start"
browser
output not displaying
Add an .babelrc file in root folder with following:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
And package.json is expected to include following dependencies:
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
Update
Also update webpack.config.js to:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./main.js",
output: {
path: path.join(__dirname, "/bundle"),
filename: "index_bundle.js"
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"
})
]
};
Check the path and change Component to component.
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path="/" component={HomePage} exact />
</div>
</Router>
);
}
}

React Router "Content Security Policy directive" error

Trying to learn React Router, get blocker when try to route the login page.
I guess it might be:
Problem in Webpack config
Skipped some meta tag
Need to change domain in Windows Host file
Dependencies problem in package.json
General info: All actions are performed locally. No server or custom domain. Just classic localhost:3000.
Steps to reproduce:
Adding manually /login to http://localhost:3000
Error:
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-GBZpdGedoBaq6YBC2+5oO7Dc8WC1XJ5EUI5Md05Lls8='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
Screen:
login page error
For more visibility here is the github repository - Project link
Webpack.config.js:
var webpack = require('webpack');
var path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
watch: true,
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
{
test: /\.(png|jp?g|gif|svg)$/,
use: [
{
loader: "url-loader",
options: { limit: 40000}
},
'image-webpack-loader'
]
}]
},
plugins: [
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
historyApiFallback: true,
files: ['./dist/*.html'],
server: { baseDir: ['dist'] }
})
]
};
App.js
import React from "react";
import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
import Home from './components/Home/Home';
import Login from './components/Login/Login';
export default () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login}/>
</Switch>
</BrowserRouter>
);
Login.js:
import React, {Component} from 'react';
import './Login.scss'
class Login extends React.Component {
render() {
return(
<div className="container2">
<h1>Login Page</h1>
</div>
)
}
}
export default Login;
package.json:
{
"name": "upstar_music",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --progress --colors",
"start": "webpack && npm run dev"
},
"author": "",
"license": "ISC",
"dependencies": {
"faker": "^3.1.0",
"lodash": "^4.17.2",
"react": "15.4.1",
"react-dom": "15.4.1",
"react-input-range": "^0.9.2",
"react-redux": "^4.4.6",
"react-router": "^3.0.0",
"react-router-dom": "^4.2.2",
"redux": "^3.6.0",
"redux-form": "^6.3.2",
"redux-thunk": "^2.1.0"
},
"devDependencies": {
"axios": "^0.18.0",
"babel-core": "^6.17.0",
"babel-loader": "^6.2.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.1.4",
"babel-preset-react": "^6.16.0",
"browser-sync": "^2.24.5",
"browser-sync-webpack-plugin": "^2.2.2",
"css-loader": "^0.26.1",
"extract-text-webpack-plugin": "^3.0.2",
"image-webpack-loader": "^4.3.1",
"node-fetch": "^2.1.2",
"node-sass": "^4.9.0",
"sass-loader": "^7.0.3",
"style-loader": "^0.13.1",
"url-loader": "^1.0.1",
"webpack": "2.2.0-rc.0",
"webpack-dev-server": "^2.11.2"
}
}
Index.js:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import '../style/style.scss';
ReactDOM.render(<App />, document.getElementById('root'));
Content Security Policy (CSP) is giving the violation simply because the CSP does not allow unsafe-inline in the Script src. For React, simply adding the hash (SHA) might not work as React simply load the script (DOM) once, when you navigate to other pages, React simply throws you "Sha-...". Another method you might look into is nonce by providing dynamic nonce. You might be able achieve from what these guys had mentioned https://stackoverflow.com/a/49890126/2875928
I was also facing the same problem, if you are using webpack simply add a new key to modules.exports named devServer as
devServer:{ historyApiFallback: true }
sharing my webpack config with devServer for reference
my working webpack configuration
for the production, if you are using nginx you can do the configuration to server same html for all requests with path being handled by react on client side.

webpack3:You may need an appropriate loader to handle this file

I guess i am missing something in webpack.config.js. When I am trying to generate bundle.js, I am getting this error.
ERROR in ./entry.js
Module parse failed: /home/rahul/project/src/entry.js Unexpected token (9:2)
You may need an appropriate loader to handle this file
|
| ReactDOM.render(
| <Router history={browserHistory}>
| <Route path="/register" component={Reg}>
| <IndexRoute component={Home}/>
package.json
{
"name": "project",
"version": "1.0.0",
"description": "React with node and express",
"main": "entry.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "Rahul singh mawari",
"license": "MIT",
"dependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"express": "^4.16.2",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-router": "^4.2.0"
},
"devDependencies": {
"babel-loader": "^7.1.2",
"http-server": "^0.10.0",
"webpack": "^3.7.1"
}
}
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var config = {
entry: path.join(__dirname,'src', 'entry.js'),
output: {
path: path.join(__dirname,'src', 'static'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js?$/,
exclude:/node_modules/,
use: ["babel-loader"],
query: {
presets: ['es2015', 'react']
}
}
]
}
};
module.exports = config;
entry.js for entry point
import react from 'react';
import Reg from './components/register';
import Home from './components/home';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from
'react-router';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/register" component={Reg}>
<IndexRoute component={Home}/>
</Route>
</Router>,
document.getElementById('app')
);
in your webpack.config.js try switching
use: ["babel-loader"],
to
loader: "babel-loader",
As the Webpack 2 migration tutorial says, the difference between use and loader is when we want an array of loaders we have to use use, if it's just one loader, we have to use loader:

after add component link error: Uncaught SyntaxError: Unexpected token export

i create test react project. Add modules and my packege.json look like:
{
"name": "untitled",
"version": "0.1.0",
"private": true,
"devDependencies": {
"babel-preset-node5": "^12.0.1",
"react-scripts": "0.9.5"
},
"dependencies": {
"babel-preset-stage-0": "^6.22.0",
"history": "^4.6.1",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-native": "^0.42.3",
"react-router": "^4.0.0",
"react-router-config": "^1.0.0-beta.1",
"react-router-dom": "^4.0.0",
"react-router-native": "^4.0.0",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.2"
},
"scripts": {
"start": "react-scripts start",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"build": "babel input.js -o compiled.js"
}
}
and webpack.config.js
var config = {
entry: './index.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', "node5", "stage-1", 'react', "stage-0"]
}
}
]
}
};
module.exports = config;
in my component i import component Link from react-router-native and after this adding react show error 'Uncaught SyntaxError: Unexpected token export' but if i delete this string project work well. it's not the only component in the module, i can add any components like Promt, Route or Router. Why it's not work with Link?
This is code where error reproduced
import React from 'react';
import { Route, Router } from 'react-router';
import { Promt } from 'react-router';
import { Link } from 'react-router-native';
import logo from '../../logo.svg';
import './App.css';
class App extends React.Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
You need to update the regular expression for the test value in your web pack config to be test: /(\.js|\.jsx)$/
Right now you are telling webpack to only run .js files through babel loader, but you aren't telling it to also run .jsx files through babel loader.

Categories