react setting without webpack - reactjs

I'm trying to set up react project without CRA
Before, I've succeed reactApp with CDN.
So this time, I just want to set up reactApp with npm.
I installed react, react-dom by npm.
and index.html below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.js"></script>
</body>
</html>
index.js below
import React from "/react";
import { ReactDOM } from "react-dom";
const createEle = React.createElement;
const domContainer = document.querySelector("#root");
const root = ReactDOM.createRoot(domContainer);
root.render(createEle(LikeButton));
function LikeButton() {
const [liked, setLike] = React.useState(false); //
if (liked) {
domContainer.style.backgroundColor = "red";
return createEle("button", { onClick: () => setLike(false) }, "Hate");
} else {
domContainer.style.backgroundColor = "green";
return createEle("button", { onClick: () => setLike(true) }, "Like");
}
}
I don't want to use webpack, babel.
but after I open the index.html, it doesn't work. Only after setting webpack, it works.
So how webpack makes reactApp alive?
Many people say that to Set up reactApp without CRA , it needs webpack because it bundles complicated so many files .
But In my case , I simplify the App and I just want to run it.
I want to know the webpack's role in my case. (the purpose i need webpack in this case

Webpack inject react and reactdom source
To use it without webpack or other module bundler you need to add react source
React cdn for development
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
React cdn for production
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
// Import is commented because script is not used as module in stack snippet. you can uncomment this.
//import React from "/react";
//import {
// ReactDOM
//} from "react-dom";
const createEle = React.createElement;
const domContainer = document.querySelector("#root");
const root = ReactDOM.createRoot(domContainer);
root.render(createEle(LikeButton));
function LikeButton() {
const [liked, setLike] = React.useState(false); //
if (liked) {
domContainer.style.backgroundColor = "red";
return createEle("button", {
onClick: () => setLike(false)
}, "Hate");
} else {
domContainer.style.backgroundColor = "green";
return createEle("button", {
onClick: () => setLike(true)
}, "Like");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<script type="module" src="./src/index.js"></script>
</body>
</html>

Related

React functional component won't display

I've started to learn React lately and today to just memorize what i've learnt i decided to create a react component that contains a simple heading tag but i can't figure out why it won't be displayed in the browser here's my code
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
</div>
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<script src="include-component.js" ></script>
</body>
</html>
and this is my react component which resides in file named include-component.js :
import React from "react";
import ReactDOM from "react-dom";
function IncludeComponent() {
return(
<TestComponent name="Hello Wolrd"/>
);
}
function TestComponent(props) {
return(
<h1>{props.name}</h1>
);
}
const app= document.getElementById('app');
ReactDOM.render(<IncludeComponent/>,app);
can someone tell me why my component won't render ?
You are using a confusing mixture of non-compiled code and compiled code. Did you checked your console? You surely have errors guiding you...
This is for when you don't have a compiler and React and ReactDOM will be available globally:
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
I don't recommend you try this approach. It is sub optimal and none of the resources you will see online are using it.
Then you do this:
<script src="include-component.js"></script>
This will already cause an exception since you're using import statements inside this JS file, but you haven't said that it type="module". Normal JS files can't use import statements.
Finally you can't import React and ReactDOM like that anyway, since you imported the browser versions which just have global variables.
Instead just start a project with Create React App:
npx create-react-app my-app
cd my-app
yarn start
And start experimenting in that instead.
For completeness you would need to transform with babel:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
</div>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.js"></script>
<script type="text/babel">
function IncludeComponent() {
return(
<TestComponent name="Hello Wolrd"/>
);
}
function TestComponent(props) {
return(
<h1>{props.name}</h1>
);
}
const container = document.getElementById('app');
const root = ReactDOM.createRoot(app);
root.render(<IncludeComponent/>);
</script>
</body>
</html>
You must import the test component!!
import TestComponent from './TestComponent';
function App() {
return (
<div className="App">
<TestComponent name='hello world' />
</div>
);
}
export default App;

How to add external JavaScript files in ReactJS

I would like to include jquery.min.js and add a external JavaScript file and call a JavaScript function inside an existing react JS file.
I did below but it is not working
const VoCaaSComponentbtn = (
<React.Fragment>
<div>
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<script type="text/javascript"src="https:xxx/microsurvey" defer="defer"></script>
<div id="microsurvey" module="true" tab-info="tabname"></div>
<script type="text/javascript"> voc_getsurvey(); </script>
</div>
</React.Fragment>
);
You can import all the scripts in the main HTML file.
If you want to import the script inside the react component, you can use the following options.
Option 1: Use plain Javascript and React custom hook
Create custom hook [useScript.js]
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
};
export default useScript;
Use
import useScript from 'hooks/useScript';
const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}
Option 2: Use plain Javascript in ComponentDidMount
componentDidMount () {
const script = document.createElement("script");
script.src = url;
script.async = true;
document.body.appendChild(script);
}
Option 3: Use dangerouslySetInnerHTML
const codeStr = `
<div>
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<script type="text/javascript"src="https:xxx/microsurvey" defer="defer"></script>
<div id="microsurvey" module="true" tab-info="tabname"></div>
<script type="text/javascript"> voc_getsurvey(); </script>
</div>
`
<div dangerouslySetInnerHTML={{ __html: codeStr }} />
You can add External JS library in indeex.html page inside public directory.
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
One another way to add external JavaScript file. If you only want to add for specific page or component.
componentDidMount() {
var script = document.createElement('script')
script.src = // path of external javascript file.
script.class = "external-script"
document.body.appendChild(script);
}

In my react application it gives error tha react and reactDOM is not defined

i am starting to create a react app and it gives error that React and ReactDOM is not defined.I am adding my code here...`
<head>
<meta charset="UTF-8">
<title>Indecision App</title>
</head>
<body>
<div id="app"></div>
<script src="https://unpkg.com/react#16.12.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.12.0/umd/react-dom.development.js">
</script>
<script src="/scripts/app.js"></script>
</body>
</html>`
And my app.js file is this
'var template = React.createElement("h1", {
id: "id"
}, "This is jsx from app.js");
var appRoot = document.getElementById('app');
ReactDOM.render(template,appRoot);`
You have not defined ReactDOM.
replace your code with this
import React from "react";
import ReactDOM from "react-dom";
var template = React.createElement("h1", {
id: "id"
}, "This is jsx from app.js")
var appRoot = document.getElementById('root');
ReactDOM.render(template,appRoot);
The below code works fine.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="https://unpkg.com/react#16.12.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.12.0/umd/react-dom.development.js"></script>
<script src="./scripts/app.js"></script>
</body>
</html>
app.js
(function() {
var template = React.createElement(
"h1",
{
id: "id"
},
"This is jsx from app.js"
);
var appRoot = document.getElementById("app");
ReactDOM.render(template, appRoot);
})();
folder structure

SyntaxError: expected expression, got '<' react json schema form

While running the sample code for react json form schema code below , I get this error {SyntaxError: expected expression, got '<'}.
Any suggestions what is incorrect here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type= "module" import React from "https://unpkg.com/react#16/umd/react.production.min.js" crossorigin></script>
<script type = "module" import { render } from "https://unpkg.com/react-dom#16/umd/react-dom.production.min.js" crossorigin></script>
<script type= "module" import Form from "https://unpkg.com/react-jsonschema-form/dist/react-jsonschema-form.js"></script>
</head>
<body>
<div id="app"></div>
<script type= "module" src="test.js"></script>
</body>
</html>
test.js
import React, { Component } from "react";
import { render } from "react-dom";
import Form from "react-jsonschema-form";
const schema = {
title: "Todo",
type: "object",
required: ["title"],
properties: {
title: {type: "string", title: "Title", default: "A new task"},
done: {type: "boolean", title: "Done?", default: false}
}
};
const log = (type) => console.log.bind(console, type);
render((
<Form schema={schema}
onChange={log("changed")}
onSubmit={log("submitted")}
onError={log("errors")} />
), document.getElementById("app"));
Hey I think you got the packages wrong ?
https://stackblitz.com/edit/react-zum7bj
check this out its working
Is test.js located in the root directory? Usually when I see that error its because script is not being imported.

ReactDOM Render of elements created with const

I am new to React. I've been following a few tutorials and the documentation.I'm trying to make the following work:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="node_modules/react/umd/react.development.js"></script>
<script src="node_modules/react-dom/umd/react-dom.development.js"></script>
<link rel="stylesheet" href="styles.css">
<title>Composable Squares</title>
</head>
<body>
<div id="container"></div>
<script src="script.js"></script>
</body>
</html>
script.js
const Title = (props) => {
    const { text } = props;
    return React.createElement('h1', null, text);
}
const App = (props) => {
    return React.createElement('div', null,
        React.createElement(Title, { text: 'Title one!' } ),
        React.createElement(Title, { text: 'Title two!!' } ),
        React.createElement(Title, { text: 'Title three!!!' } )
    )
}
ReactDOM.render(App, document.getElementById('container'));
I'm getting the following message:
Warning: Functions are not valid as a React child. This may happen if
you return a Component instead of from render. Or maybe
you meant to call this function rather than return it.
I've tried changing it to: ReactDOM.render(<App />, document.getElementById('container')) and I get Unexpected token <
How can I render the elements created by App?
Your App is a function. ReactDOM.render() expects an element as argument, not a function.
The quickest solution is to just invoke App():
ReactDOM.render(App(), document.getElementById('container'));
Or you can make App not a function, but assign to it the result of React.createElement('div'....
Demo:
const Title = (props) => {
const { text } = props;
return React.createElement('h1', null, text);
}
const App = (props) => {
return React.createElement('div', null,
React.createElement(Title, { text: 'Title one!' } ),
React.createElement(Title, { text: 'Title two!!' } ),
React.createElement(Title, { text: 'Title three!!!' } )
)
}
ReactDOM.render(App(), document.getElementById('container'));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript" src="//unpkg.com/react/umd/react.development.js"></script>
<script type="text/javascript" src="//unpkg.com/react-dom/umd/react-dom.development.js"></script>
<link rel="stylesheet" href="styles.css">
<title>Composable Squares</title>
</head>
<body>
<div id="container"></div>
<!-- script src="script.js"></script -->
</body>
</html>
When you use this,
ReactDOM.render(<App />, document.getElementById('container'))
You are getting error, because you are using JSX so you need a babel.
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
Also make sure when you add babel, you must add type="text/babel" on your script tag,
<script type="text/babel" src="script.js"></script>
Demo
Read how to Add React to a Website.

Resources