React / Webpack component not showing, what's wrong - javascript

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

Related

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>

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 Hot loader 3 with webpack-dev

I'm trying to use hot-react-loader in my project.
So I changed some files to work with this but I get an error when I edit a component.
Warning: React.createElement: type should not be null, undefined,
boolean, or number. It should be a string (for DOM elements) or a
ReactClass (for composite components).
[HMR] Cannot apply update. Need to do a full reload!
what am I doing wrong?
webpack.config.dev.js
var webpack = require('webpack');
var path = require('path');
// Questo il plugin di webpack che mi genera il file index.html in dist
var HtmlwebpackPlugin = require('html-webpack-plugin');
const PATHS = {
app: path.join(__dirname, 'app/index'),
build: path.join(__dirname, 'dist')
};
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3500',
'webpack/hot/only-dev-server',
'react-hot-loader/patch',
PATHS.app
],
output: {
path: PATHS.build,
filename: 'js/bundle.js'
},
// Questo serve a non specificare le estensioni
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{ test: /\.(png|jpg)$/, loader: "file?limit=1000&name=images/[hash].[ext]" },
{ test: /\.scss$/, loaders: [ 'style','css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]' ] }
]
},
// Porta utilizzata da webpack-dev-server
devServer: {
port: 3500
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlwebpackPlugin({
title: 'React Starter Kit',
hash: true,
inject: false,
appMountId: 'app',
template: 'jade!./app/assets/index.jade'
})
]
};
server.js
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config.dev');
new WebpackDevServer(webpack(config), {
hot: true,
historyApiFallback: true,
stats: {
colors: true
}
}).listen(3500, 'localhost', function (err) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3500');
});
index.js
import ReactDOM from 'react-dom';
import React from 'react';
import App from './app';
import { AppContainer } from 'react-hot-loader';
const root = document.getElementById('app');
ReactDOM.render(
<AppContainer>
<App />
</AppContainer>
, root);
if (module.hot) {
module.hot.accept('./app', () => {
const App = require('./app');
ReactDOM.render(
<AppContainer>
<App />
</AppContainer>
, root);
});
}
app.js
import React from 'react';
import { Router, browserHistory } from 'react-router';
import routes from './routes/routes';
const App = () => (
<Router history={browserHistory} routes={routes} />
);
export default App;
You have to modify the prototype chain of the Router component itself to force render the new stuff.
// Router
import { Router, browserHistory } from 'react-router'
if (process.env.NODE_ENV === 'production') {
// ...
} else {
// the hacky workaround
Router.prototype.componentWillReceiveProps = function (nextProps) {
let components = [];
function grabComponents(routes) {
routes.forEach((route) => {
if (route.component) {
components.push(route.component)
}
if (route.indexRoute && route.indexRoute.component) {
components.push(route.indexRoute.component)
}
if (route.childRoutes) {
grabComponents(route.childRoutes)
}
})
}
grabComponents(nextProps.routes)
components.forEach(React.createElement) // force patching
}
}
The code you see here is an adaptation of https://github.com/gaearon/react-hot-boilerplate/pull/61#issuecomment-211504531

Trying to make React Hot, Express and Webpack work together

I'm a backend guy that has decided to learn some frontend, but it seems that I'm pretty far from learning since I can't even configure the environment.
My goal is to setup Webpack with Babel 6, React, react-hot and HotModuleReplacementPlugin. I also want the app to have express.js server. So here're my configs:
server.js:
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')
var app = new (require('express'))()
var port = 4000
var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html')
})
app.listen(port, function(error) {
if (error) {
console.error(error)
} else {
console.info("==> http://localhost:%s/", port)
}
})
webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:4000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
preLoaders: [
{ test: /\.jsx?$/, loader: 'eslint', exclude: /node_modules/ }
],
loaders: [
{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=stage-0,presets[]=react,plugins[]=transform-runtime'],
include: path.join(__dirname, 'src')
}
]
}
}
public/index.html
<html>
<head>
<title>React setup</title>
</head>
<body>
<div id='root'>
</div>
<script src='bundle.js'></script>
</body>
</html>
src/App.js
import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<h1>Hello, world!</h1>
);
}
}
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
And here's what I've got in my console (the error is looped):

React router dynamic routes not rendering component

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.

Categories