ReactDOM Render of elements created with const - reactjs

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.

Related

react setting without webpack

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>

How do I create NextJS script to embed in another html file?

Let's say I have a card component/page that I created using tailwindcss and typescript like this
type CardProps = {
config: {
title: string;
clickMeButtonText: string;
}
}
const Card = ({ config } : CardProps) => {
const func = () => {
console.log("func called!");
}
return (
<div>
<h1 className="text-3xl font-bold">{config.title}</h1>
<button onClick={func} className="bg-gray-400 text-black">{config.clickMeButtonText}</button>
</div>
);
}
export default Card;
I want to call this component in another html file as follows.
<!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>
<script src="my-domain.com/card/bundle.js"></script>
<script>
init({
title: 'My Card',
clickMeButtonText: 'Click Me',
})
</script>
</body>
</html>
I know I didn't define a function called init but I gave such an example to show how I want to call it. Can I create such a structure using nextjs?

Why is React Slower at creating a list of 10,000 items then standard DOM calls?

I'm trying to show that React is faster at rendering a simple list because the virtual DOM only has to update the DOM once, where as using rootELement.appendChild() should have to create thousands of round trips to the DOM.
The console.log shows WithReact is about 1600ms on average and without, about 1300ms
Here is my Code with no React
<!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>No React</title>
</head>
<body>
<div id="root">
</div>
<script>
const rootElement = document.getElementById("root");
let list = document.getElementById("myList");
[...Array(10000).keys()].forEach((item) => {
let li = document.createElement("li");
li.innerText = item;
rootElement.appendChild(li);
});
console.log("done with list creation");
</script>
<script>
var renderStart = new Date().getTime();
window.onload = function () {
var elapsed = new Date().getTime() - renderStart;
console.log("No React: Rendered in " + elapsed + "ms");
};
</script>
</body>
</html>
And here is the code with React
<!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>Simple React No JSX</title>
<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>
</head>
<body>
<div id="root"></div>
<script>
const rootElement = document.getElementById("root");
const root = ReactDOM.createRoot(rootElement);
const childrenElements = [...Array(10000).keys()].map((id) => {
return React.createElement("li", { key: id }, id);
});
const element = React.createElement("ul", null, childrenElements);
root.render(element);
</script>
<script>
var renderStart = new Date().getTime();
window.onload = function () {
var elapsed = new Date().getTime() - renderStart;
console.log("WithReact: Rendered in " + elapsed + "ms");
};
</script>
</body>
</html>

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.

Resources