React router dynamic routes not rendering component - javascript

I’m trying to get react router dynamic routing to work by following this example: https://github.com/rackt/react-router/tree/master/examples/huge-apps
Here’s my setup:
webpack.config.js:
module.exports = {
devtool: 'inline-source-map',
entry: './js/app.js',
output: {
path: '../public',
filename: 'test-app.js',
chunkFilename: '[id].chunk.js',
publicPath: '/public/'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: [
'es2015',
'react'
]
}
}
]
}
./js/app.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { createHistory, useBasename } from 'history';
import { Router } from 'react-router';
const history = useBasename(createHistory)({
basename: '/'
});
const rootRoute = {
component: 'div',
childRoutes: [{
path: '/',
component: require('./components/App')
}]
};
ReactDOM.render(
<Router history={history} routes={rootRoute} />,
document.getElementById('root')
);
./components/App.js:
import React from 'react';
console.log('testing');
export default class App extends React.Component {
render() {
console.log('App');
return (
<div>
App!
</div>
)
}
}
index.html:
<!doctype html>
<html>
<head>
<title>Test App</title>
</head>
<body>
Hello
<div id="root"></div>
<script src="public/test-app.js"></script>
</body>
</html>
When I run the server, I see Hello displayed from index.html, I also see console.log('testing') from App.js, but the actual App.js component does not render. Any ideas why?
Thanks!
EDIT:
If I change ./components/App.js to ES5 syntax below, it works! Why is that? Does react router's component: require('./components/App') not work with ES6?
var React = require('react');
var App = React.createClass({
render: function() {
return (
<div>
App!
</div>
)
}
});
module.exports = App;

I think, you are using Babel 6, where they changed commonjs require syntax.
Now, you need to add the default:
component: require('./components/App').default
I had the same problem, finally found how to make it work.

Related

How do I solve object or props is not defined in ReactJS?

I am using a basic codebase in React that uses Webpack to compile ES6 and JSX to be backwards compatible.
I created a component using ES6 syntax and I want to display a props value into the component but I get an error in the console that says:
Uncaught ReferenceError: myCheese is not defined
at Module../src/index.js (index.js:8)
at webpack_require (bootstrap:18)
at startup:3
at startup:5
App.js
import React from "react";
import { hot } from "react-hot-loader";
class App extends React.Component {
render() {
return (
<div>
<p>Another paragraph</p>
<p>{this.props.msg}</p>
<p>
<strong>Cheese name: </strong> {this.props.cheese.name}
</p>
</div>
);
}
}
var myCheese = {
name: "Camembert",
smellFactor: "Extreme pong",
price: "3:50",
};
export default hot(module)(App);
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./styles.css";
// put component into html page
ReactDOM.render(
<App msg="I like cheese" cheese={myCheese} />,
document.getElementById("app")
);
webpack.config.base.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, "dist"),
filename: "app.bundle.js",
},
module: {
...
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
};
Any help is greatly appreciated. Thanks.
You have myCheese in App.js rather than index.js
Try moving this block of code into index.js
var myCheese = {
name: "Camembert",
smellFactor: "Extreme pong",
price: "3:50",
};

React Router gives 404 if I try to copy and paste url in new tab

I am not sure if react router is not working correctly or if I am missing something.
I have something like this
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import { configure } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router'
import AppContainer from './components/App';
const browserHistory = createBrowserHistory();
import stores from '../src/stores/Stores';
const history = syncHistoryWithStore(browserHistory, stores.routingStore);
configure({ enforceActions: true});
ReactDOM.render(
<Provider {... stores}>
<Router history={history}>
<AppContainer />
</Router>
</Provider>,
document.getElementById('app')
);
Then in my AppContainer I have this
import { withRouter, Route, Link } from "react-router-dom";
<Route path="/company-details/company/:companyId/employee/:employeeId" component={CompanyComponent} />
and
<Link to="/company-details/company/76/employee/77"></Link>
now when I click on the link, it goes to the right page and I got access to the parameters.
but say if I did ctrl + click to make a new tab while clicking on the link or refreshing the page.
I get
GET http://localhost:8080/company-details/company/76/employee/index_bundle.js 404 (Not Found)
Refused to execute script from 'http://localhost:8080/company-details/company/76/employee/index_bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I have these packages installed
"react-router-dom": "^4.2.2"
"mobx-react-router": "^4.0.4",
Edit
my webpack.config
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
path: path.join(__dirname, "/dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /(\.css|\.scss|\.sass)$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
},
{
loader: "sass-loader" // compiles Sass to CSS
}
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
devServer: {
historyApiFallback: true
}
};
Inside index.html you should link your script file like following:
<script type="text/javascript" src="./index_bundle.js"></script>

Why does webpack ignore the index.js although it's in the same directory of my app.js, which is compiled fine

I am building a simple form with react, using webpack. I'm new to webpack and react, so there might be an obvious solution, but I just can't figure it out.
My code structure (simplified):
root:
- server.js
- webpack.config.js
- src:
-- App.js
-- index.js
- public:
-- index.html
-- bundle.js
In my app.js is only one Component. I have excluded the ReactDOM.render method into a file index.js. Since i've done that it doesn't work anymore. Before it worked just fine.
The App isn't rendered into my index.html anymore. I guess webpack compiles only my app.js file and ignores my index.js. But I can't know for sure.
When I include the index.js into my App.js everything works just fine.
// /src/App.js
import React, {Component} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
form: 'firmenkontakt'
}
};
render() {
return (
<div className={this.state}>
<form method="post" id={this.state}>
...
</form>
</div>
)
}
}
export default App;
The rendering-file looks as follow:
// /src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('app'));
registerServiceWorker();
I wonder if anything is wrong about my webpack.config.js
// /webpack.config.js
let path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/App.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
watch: true,
module: {
loaders: [
{
test:/\.js$/,
exclude: /node_module/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}
]
}
}
Your entry file should be src/index.js' and it must importApp.js`

How to serve static Image path in img tag with webpack in React JS application

I am working on a React application where in I am having img tag with hard coded image path like below in render function
import '../css/styles.scss';
import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import { List } from './list';
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="container">
< img src="images/logo.png" alt=""/>
);
}
}
const root = document.getElementById('app-container');
ReactDom.render(<App />, root);
When I run application with webpack-dev-server, application runs fine and I can see image o webpage. However when i run application using webpack command, it generates build folder and and when I run application; I can't see image in webpage.
my webpack.config.js is :
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolve } = require('path');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
resolve(__dirname, 'src', 'js/app.js'),
],
output: {
filename: '[name].[hash].js',
path: resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader?sourceMap&camelCase&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass-loader?sourceMap'
]
}
},
plugins: [
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: resolve(__dirname, 'src', 'index.html')
})
]
}
I understand we can use file-loader in webpack to generate image folder in build folder and use import image from "__path to image"
However is there any way to serve direct image path mention in render function above ?
Thanks in advance
One solution is to use CopyWebpackPlugin. This will copy your images from your src folder to build folder. Then your app can resolve the relative urls.
var CopyWebpackPlugin = require('copy-webpack-plugin');
....
plugins: [
new CopyWebpackPlugin([
{ from: './src/images', to: 'images' },
]),
]
one solution is you have to install url-loader.This is command
npm install --save-dev url-loader
then add following code in webpack.config file in your rules section.
{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=25000'
},
next import your image in your APP component.
import logo from 'images/logo.png';
and pass logo in img tag.Like this
< img src={logo} alt=""/>
import '../css/styles.scss';
import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import { List } from './list';
import logo from 'images/logo.png';
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="container">
< img src={logo} alt=""/>
);
}
}
const root = document.getElementById('app-container');
ReactDom.render(<App />, root);

React / Webpack component not showing, what's wrong

This is all new and no doubt I'm doing something stupid, but I have a component that I can't get to show up.
Here's my webpack.config.js
var path = require('path');
var webpack = require('webpack');
var bootstratp = require('react-bootstrap');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
output: {
path: path.join(__dirname, 'dist'),
//path: 'build',
filename: 'bundle.js',
publicPath: '/static/'
},
resolve:{
extensions:['','.js','.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
};
Here's the index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
Here's the App.js
import React, { Component } from 'react';
import {Button} from 'react-bootstrap';
import TestBox from './components/test';
var path = require('path');
export default class App extends Component {
render() {
return (
<div>
<h1>aaa</h1>
<TestBox/>
</div>
);
}
}
Finally here's the component that isn't showing up:
export default
TestBox = React.createClass({
render:function(){
return <div>ABCD</div>
}
});
You don't need to put an equal sign in front of the export default:
try this, similar to how you have it in App.js:
let TestBox = React.createClass({
render:function(){
return <div> ABCD </div>
}
});
export default TextBox

Categories