Cannot import materialize-css in React project to use Chips - javascript

I have created project by command:
create-react-app app
I am using materialize-css http://materializecss.com/ and want to use Chips http://materializecss.com/chips.html.
import React, { Component } from 'react';
import $ from 'jquery';
import 'materialize-css';
class Form extends Component {
constructor(props) {
super(props);
$(document).ready(function() {
$('.chips').material_chip({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
});
}
render() {
return (
<div>
<div className="chips"></div>
<button>Add</button>
</div>
)
}
}
I have tried to import:
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js'
But it's not working. The browser throw error:
Uncaught TypeError: $(...).material_chip is not a function

Try this in your entry JS file
import 'materialize-css'; // It installs the JS asset only
import 'materialize-css/dist/css/materialize.min.css';
and you are done!
Update:
I have put all the necessary details to get your code working. Try this out
index.jsx file is here
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';
class Form extends Component {
constructor(props) {
super(props);
$(document).ready(function() {
$('.chips').material_chip({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
});
}
render() {
return (
<div>
<div className="chips"></div>
<button>Add</button>
</div>
)
}
}
ReactDOM.render(<Form />, document.getElementById('app'));
and package.json is like
"dependencies": {
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"font-loader": "^0.1.2",
"jquery": "^3.1.1",
"materialize-css": "^0.97.8",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"redux": "3.6.0",
"style-loader": "^0.13.1"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.18.0",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2",
"webpack-hot-middleware": "^2.15.0"
}
and webpack.config.js is
const webpack = require('webpack');
module.exports = {
entry: [Screenshot from 2017-01-15 18-11-16
"./src/index.jsx",
"webpack-dev-server/client?http://localhost:3000/",
"webpack/hot/only-dev-server"
],
output: {
filename: "bundle.js",
path: __dirname + '/public'
},
devServer: {
contentBase: './public',
port: 3000
},
// Bundle lookup dir for included/imported modules
// By default, bundler/webpack with search here for the scripts
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js', '.jsx']
},
// make sure you added babel-loader to the package
// npm i babel-loader babel-core babel-preset-es2015 -D
module: {
loaders: [
{
test: /\.js[x]?$/, // Allowing .jsx file to be transpiled by babel
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{ test: /\.css$/, loaders: [
'style',
'css?importLoaders=1',
'font?format[]=truetype&format[]=woff&format[]=embedded-opentype'
] },
{ test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]' }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
No error whatsoever.

With NPM:
Step 1: Install materialize
If you are using npm, make sure you install materialize using the command listed in their documentation:
npm install materialize-css#next
DON'T MISS the '#next' at the end. The installed version will be something like: "^1.0.0-rc.2" OR "^1.0.0-alpha.4"
Step 2: Import materialize:
import 'materialize-css/dist/css/materialize.min.css'
import M from 'materialize-css/dist/js/materialize.min.js'
OR
import 'materialize-css/dist/css/materialize.min.css'
import M from 'materialize-css'
In order for the css import to work, you would need a css loader. Note that this loader is already included in projects built using create-react-app so you don't need the next steps. If instead, you are using custom webpack config, then run:
npm install --save-dev style-loader css-loader
Now add css-loader and style-loader in webpack config
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "build")
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}
]
}
}
Now you can initialize components individually, or all at once using M.AutoInit();
With CDN:
Add the following in your HTML file.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
Then, in the webpack config, add externals: https://webpack.js.org/configuration/externals/

Related

Failed to resolve import "React" in npm package and webpack 5

I am developing a npm package and use there webpack 5.
This is my config
const path = require('path') // resolve path
module.exports = {
mode: 'development',
resolve: {
extensions: ['.js', '.jsx'], // we can import without typing '.js or .jsx'
},
entry: {
index: path.join(__dirname, 'src/index.jsx'),
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index.js', // for production use [contenthash], for developement use [hash]
library: {
type: 'module',
},
environment: { module: true },
},
experiments: {
outputModule: true,
},
devtool: 'eval',
module: {
rules: [
{
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: /\.(js|jsx)$/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(png|svg|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
{
test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
exclude:
/images/ /* dont want svg images from image folder to be included */,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts/',
name: '[name][hash].[ext]',
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
plugins: [],
}
When I want to import components from this library I get this error:
Failed to resolve import "React" from "..my-package/dist/index.js". Does the file exist?
I think this has something to do with externals react and react-dom. But when I remove the externals from webpack config I get the error that react should be only installed once when using react hooks.
In my main application I am using vite for bundeling but I tried it also with create-react-app and have the same problem.
My Library Component:
import React, { useState } from 'react'
const App = () => {
const [counter, setCounter] = useState(0)
return <div>{counter}</div>
}
export default App
This is how I am using it with npm-link:
import React from "react";
import Test from "my-package";
const App = () => {
return <Test />;
};
export default App;
Here is the repo with the code https://github.com/guitar9/webpack-bug

React component error: expected a string or a class/function but got undefined

I am getting the following error in a create-react-app. Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
The app is currently a super-basic - it just imports and renders one single component:
import './App.css';
import { PasswordInput } from 'gg-react-test-lib';
function App() {
return (
<div className="App">
<PasswordInput />
</div>
);
}
export default App;
I am therefore assuming that the problem is with my component library that I am importing the PasswordInput component from. I am installing it from NPM.
It has an index.js file like:
import Radio from './Radio/Radio';
export { PasswordInput, Radio }```
Those component files themselves do a default export at the bottom of the file e.g.:
`export default PasswordInput;`
I have a pretty minimal webpack.config.js file in my component library repo:
```const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader"
}
]
},
output: {
path: path.resolve(__dirname, "dist/"),
filename: 'bundle.js'
},
optimization: {
minimizer: [new TerserPlugin()]
},
};
My package.json:
{
"name": "gg-react-test-lib",
"version": "1.0.7",
"description": "",
"main": "dist/bundle.js",
"module": "src/index.js",
"author": "",
"license": "ISC",
"dependencies": {
"clsx": "^1.0.4",
"node-sass": "^4.13.0",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"scripts": {
"build": "webpack"
},
"devDependencies": {
"#babel/cli": "^7.7.5",
"#babel/core": "^7.7.5",
"#babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"webpack": "^4.41.3",
"webpack-cli": "^3.3.10"
}
}
.babelrc file:
{
"presets": [
"#babel/preset-react"
]
}

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>
);
}
}

How to use React.js with AdonisJs

How can I use React.js in the front-end of my AdonisJs project?
I've tried to install react with npm install react I thought this will works correctly. I made a file app.js with this code:
var React = require('react');
var ReactDOM = require('react-dom');
export default class Index extends Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'))
But this isn't working at all, I don't know what to do more I have searched about how to use React in Adonis but I didn't find anything interesting.
I strongly suggest you to use WebPack for this task.
create a webpack.config.js file in your root directory:
maybe your code need some changes but this is the idea:
const webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var pkgBower = require('./package.json');
module.exports = {
target: "web",
devtool: "source-map",
node: {
fs: "empty"
},
entry: {
'app': path.join(__dirname, 'react-app', 'Index.jsx')
},
resolve: {
modules: [__dirname, 'node_modules', 'bower_components'],
extensions: ['*','.js','.jsx', '.es6.js']
},
output: {
path: path.join(__dirname, 'public', 'src'),
filename: '[name].js'
},
resolveLoader: {
moduleExtensions: ["-loader"]
},
module: {
loaders: [
{
test: /jquery\.flot\.resize\.js$/,
loader: 'imports?this=>window'
},
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react', 'stage-0'],
compact: false
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
loader: 'url?prefix=font/&limit=10000'
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url?limit=10000'
},
{
test: /\.scss$/,
loader: 'style!css!sass?outputStyle=expanded'
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new CopyWebpackPlugin([{
from: 'img',
to: 'img',
context: path.join(__dirname, 'react-app')
}, {
from: 'server',
to: 'server',
context: path.join(__dirname, 'react-app')
}, {
from: 'fonts',
to: 'fonts',
context: path.join(__dirname, 'react-app')
}]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
mangle: true,
sourcemap: false,
beautify: false,
dead_code: true
}),
new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /js$/)
]
};
Then put your app in your root directory, in a folder react-app/ and your components can go inside that folder:
For example your file: [Index.jsx]
import React from 'react';
import ReactDOM from 'react-dom';
class Index extends Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'));
you don't need to export this Index component in this case, but in case you need to just use export default ComponentName at the end of your component file.
The next step is in your routes file (I'm using AdonisJS 4) but is very similar for the version 3.x
Route.any("*", ({ view, response }) => (
view.render('index')
))
Then your index (.njk, or .edge) file (under resources/views) should look something like this:
<html>
<head>
<link rel="stylesheet" href="/src/styles.css">
<script type="text/javascript" src="/src/app.js"></script>
</head>
<body>
<div id="example"></div>
</body>
</html>
--
You need to install some npm/ packages with npm or yarn,
and remember to run in another terminal window or tab,
webpack -d --watch --progress
Regards.
This works. You are missing React.Component.
var React = require('react');
var ReactDOM = require('react-dom');
export default class Index extends React.Component {
render() {
return (< h1 > hello world! < /h1>)
}
}
ReactDOM.render( < Index / > , document.getElementById('example'))
Alternatively you can use import React, {Component} from 'react'; if you want to use your code structure.
For decoupled use, just build your React app and copy the build to Adonis public folder.

Learning ReactJS: Uncaught SyntaxError: Unexpected token import

I'm new to ReactJS. I'm trying out the code from egghead.io and I keep getting the following error:
Uncaught SyntaxError: Unexpected token import
I have loaded babel twice now and have followed along the lesson as described, but it just won't load into the html page. Here is the codes:
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Setup</title>
</head>
<body>
<div id = "app"></div>
<script src = "main.js"></script>
</body>
</html>
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App2';
ReactDOM.render(<App />, document.getElementById('app'))
app2.jsx
import React from 'react';
import ReactDom from 'react-dom';
class App extends React.Component {
render(){
let txt = this.props.txt
return <h1>{txt}</h1>
}
}
App.propTypes = {
txt: React.PropTypes.string,
cat: React.PropTypes.number.isRequired
}
App.defaultProps = {
txt: 'this is the default txt'
}
ReactDOM render(
<App cat={5}/>,
document.getElementById('app')
)
package.json
{
"name": "es6-react-setup",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^0.14.3",
"react-dom": "^0.14.3"
},
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5"
}
}
Please help.
After installing the Babel presets for ES6 and React you need to enable them either by creating a .babelrc file or by opting in in your package.json file.
(Confusing) docs here: http://babeljs.io/docs/usage/babelrc/
Example package.json entry enabling the presets:
"babel": {
"presets": [
[
"env",
{
"modules": false
}
],
"react"
]
}
import is the ES6 syntax. You need to npm install babel-preset-es2015 babel-preset-react --save-dev to tell babel compile your ES6 and React code.
you can load 2 packages in your webpack.config.js file :
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
I hope it will help you.

Categories