How to add React component to a website using babel - javascript

I'm trying to add a React component to a website using babel. Here's official React documentation tutorial but I could not make it work.
Here's my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="#000000"/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://unpkg.com/react#18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js" crossorigin></script>
<script src="build/index.js" type="text/babel"></script>
</body>
</html>
Here's my src/index.js
import React from 'react'
import ReactDOM from 'react-dom/client'
function App() {
return (
<button>Like me!</button>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Here's my package.json
{
"name": "react-project",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/cli": "^7.20.7",
"#babel/core": "^7.20.12",
"#babel/preset-react": "^7.18.6"
}
}
Then I run in terminal:
./node_modules/.bin/babel src --out-dir build --presets #babel/preset-react
It creates build/index.js which is added to my index.html:
import React from 'react';
import ReactDOM from 'react-dom/client';
function App() {
return /*#__PURE__*/React.createElement("button", null, "Like me!");
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( /*#__PURE__*/React.createElement(App, null));
When I open index.html in browser - nothing happens, button does not appear.
This whole story works only if I add <script src="https://unpkg.com/#babel/standalone/babel.min.js"></script> to my index.html but this is not what I want.
What do I do wrong?

because babel only compiles jsx the esm syntax remains and you have nothing to deal with them (a compiler or esm itself with type='module' and cdn esm or importmap)
for starters use powerful tools like vite

Related

Gatsby: 404 page thrown on browser navigation

Gatsby v3 is throwing a 404 page if I navigate to a route with browser buttons instead of clicking on a link. How can I fix this issue?
Steps to Reproduce
Start the Gatsby project with gatsby develop command.
Navigate from index page to about page by clicking on link.
Refresh the browser on about page.
Click on browser's back navigation.
For an unknown reason index page throws 404 page instead.
GIF
You may refer to the GIF attached below for better clarity.
Index Page: src/pages/index.js
import React from 'react';
import { Link } from 'gatsby';
const IndexPage = () => {
return (
<main>
<h1>Index Page</h1>
<Link to="/about">About Me</Link>
</main>
);
};
export default IndexPage;
About Page: src/pages/about.js
import React from 'react';
import { Link } from 'gatsby';
const AboutPage = () => {
return (
<main>
<h1>About Page</h1>
<Link to="/">Back To Home</Link>
</main>
);
};
export default AboutPage;
Package.json
{
"name": "my-gatsby-site",
"version": "1.0.0",
"private": true,
"description": "My Gatsby Site",
"keywords": [
"gatsby"
],
"scripts": {
"develop": "gatsby develop",
"start": "gatsby develop",
"build": "gatsby build",
"serve": "gatsby serve",
"clean": "gatsby clean"
},
"dependencies": {
"gatsby": "^3.6.2",
"gatsby-plugin-gatsby-cloud": "^2.8.1",
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}

"Uncaught Error: Cannot find module 'react'" keeps showing

I really wonder why it keeps showing me this error message
Uncaught Error: Cannot find module 'react'
although I have tried every single solution that I have found on the posts below:
Uncaught Error: Cannot find module "react"
"[ts] Cannot find module 'react'" in spite of "npm install"
Uncaught Error: Cannot find module 'react'
Cannot find module 'react'
These are the scripts I have put in my relevant files:
welcome.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
</head>
<body>
<div id="example"></div>
<script src="js/app.js"></script>
</body>
</html>
app.js:
require('./bootstrap');
require('./components/Example');
Example.js:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, NavLink } from 'react-router-dom';
import Home from './Home';
import { Link } from 'react-router/lib/Link';
class Example extends Component{
render(){
return(
<BrowserRouter>
<div>
<NavLink to="/home">Home</NavLink>
<Switch>
<Route path="/home" component={Home}/>
</Switch>
</div>
</BrowserRouter>
)
}
}
export default Example;
if(document.getElementById('example')){
ReactDOM.render(<Example />, document.getElementById('example'));
}
Home.js:
import React, { Component } from 'react';
class Home extends Component{
render(){
return(
<div>
</div>
)
}
}
export default Home;
package.json:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production"
},
"devDependencies": {
"#babel/preset-react": "^7.12.13",
"axios": "^0.21.1",
"laravel-mix": "^6.0.11",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"resolve-url-loader": "^3.1.2",
"sass": "^1.32.6",
"sass-loader": "^8.0.2"
},
"dependencies": {
"#types/react": "^17.0.1",
"#types/react-dom": "^17.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0"
}
}
webpack.mix.js:
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/
/* mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
//
]); */
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.react();
So, what is wrong in my code? Any idea?
P.S:
React JS version: 17.0.1
Node.js version: v15.7.0
This solved the issue for me.
Open up the terminal and type in
yarn add typescript --dev
if using npm type in
npm install typescript

Embedded react component not rendered/loaded in html page. (webpack/babel)

I am trying to set up my first Webpack Babel React project.
Although the html code shows on various browsers (http://localhost:80), the embedded react component is not loaded. The following message can be read in the console
"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (transformed.js:304)"
Click here to see error image
Find below the different config and code files setting up this environment.
./app/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first local App</title>
</head>
<body>
<div id='app'> </div>
<h1> Testing </h1>
</body>
</html>
./app/index.js
var React = require('react');
var ReactDOM = require('react-dom');
var App = require('../components/App');
ReactDOM.render(
<App />,
document.getElementById('app')
);
./components/App.js
import React from 'react';
import ReactDOM from 'react-dom';
export class App extends React.Component {
constructor(){
super();
console.log('Component has been constructed ')
}
render() {
return (
<div>
<h1>This is a simple test</h1>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
package.json
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"deploy":"npm run build && npm run git-commit && npm run git-push",
"build": "webpack",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
}
}
.babelrc
{presets:["react"]}
webpack.config
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin ({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: __dirname + '/app/index.js' ,
module: {loaders: [ {test:/\.js$/, exclude:/node_modules/, loader:'babel-loader' } ]},
output: {filename: 'transformed.js', path: __dirname + '/build'},
plugins: [HTMLWebpackPluginConfig],
resolve : { extensions: [".js", ".jsx"] }
};
Thanks,
Sebastian
Looks like you have
ReactDOM.render(
<App />,
document.getElementById('app')
);
in there twice. Could be other errors as well, but remove it from App.js and see if that helps.
At first, remove second render in <App />, at second, change var App = require('../components/App'); to import {App} from '../components/App'; And your error must gone.

Deploying react app with webpack server

I am a beginner in ReactJS and was just exploring it and trying to configure it with Webpack and Babel when I experienced an error when I run the application using npm start.
Following are some of files:-
package.json
{
"name": "reactstarter",
"version": "1.0.0",
"description": "A basic React application to explore its state and beauty",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"keywords": [
"reactjs"
],
"author": "user1705",
"license": "MIT",
"dependencies": {
"debug-log": "^1.0.1",
"react": "^15.3.2",
"react-dom": "^15.3.2"
},
"devDependencies": {
"webpack": "^1.13.2"
}
}
There are two directories src directory and dist directory inside the root folder.
File: src/index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "/app/bundle.js"></script>
</body>
</html>
File:- src/app/App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
File:- src/app/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
And webpack.config.js:-
var webpack= require(webpack);
var path= require(path);
var DIST_DIR=path.resolve(__dirname,"dist");
var SRC_DIR= path.resolve(__dirname,"src");
var config={
entry:SRC_DIR+"/app/index.js",
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
devServer: {
inline: true,
port: 7777
},
modules:{
loaders:[
{
test:/\.js?/,
include:SRC_DIR,
loader:"babel-loader",
query:{
presets:["react","es2015","stage-2"]
}
}
]
}
};
module.exports=config;
So now whenever I run the command npm start,it gives the following error:-
Being a beginner I have no idea as what is the issue?? If anyone has come across this similar issue or knows about the error,please contribute your knowledge and show me the right path.
change
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
to
output:{
path:DIST_DIR+"/app",
fileName:"bundle.js",
publicPath:"/app/",
},
It seems that you forgot the quotes when you were requiring the npm modules:
var webpack= require('webpack');
var path= require('path');

Facing some issues with ReactJS first program

I just started learning ReactJS, I am following this tutorials here.
egghead.io I just completed its first video and developed an app as shown in video, But some how I can see the html part but failed to load the dynamic content coming from the App.js Below is my code:
App.js
import React from 'react';
class App extends React.Component {
// always expected to return
render() {
return '<div><h4>Hello World of ReactJS</h4></div>'
}
}
export default App;
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Tutorial</title>
</head>
<body>
<h1>ReactJS First Project</h1>
<div id="app">
</div>
<script src="index.js"></script>
</body>
</html>
main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render('<App/>' , document.getElementById('app'));
package.json
{
"name": "App",
"version": "1.0.0",
"description": "First application of ReactJS",
"private": true,
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "AD",
"license": "Apache",
"dependencies": {
"babel-core": "^6.13.1",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.1",
"babel-preset-react": "^6.11.1",
"react": "^15.3.0",
"react-dom": "^15.3.0"
},
"devDependencies": {
"webpack-dev-server": "^1.9.0"
}
}
webpack.config.js:
module.exports = {
entry: "./main.js",
output: {
path: "./",
fileName: "index.js"
},
devServer: {
inline: true,
port: 3333
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
Would need some help to run it, not sure. I have installed everything as asked in the video, I am using node 6.2.2.
In your main.js, change:
ReactDOM.render('<App/>' , document.getElementById('app'));
to
ReactDOM.render(<App/>, document.getElementById('app'));
The quotes are the problem. You want to render your imported component, not some String. Also I would be interested if you got a warning in the console.

Categories

Resources