Simple react component does not render [duplicate] - javascript

This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 9 months ago.
I've been trying to figure out why my components will not display at all for the past 5 hours. Any help is greatly appreciated.
Here is the source:
index.html:
<!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">
<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="modules/Container.js"></script>
<script src="modules/CategoryFolder.js"></script>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script>
let root = $('#root')[0];
reactroot = ReactDOM.createRoot(root);
reactroot.render(React.createElement(Container));
</script>
</body>
</html>
modules/Container.jsx:
const SPACING = 10;
class Container extends React.Component {
constructor() {
super();
this.state = {categories: []};
}
componentDidMount() {
$.ajax({
url: './items/categories',
dataType: 'json',
async: true,
success: (categories) => {
this.setState({categories});
}
})
}
render() {
this.state.categories.map((category, i, a)=>{
<CategoryFolder style={{'z-index':i,top:i*SPACING+'%'}} CategoryTitle={category}></CategoryFolder>
})
}
}
modules/CategoryFolder.jsx:
function CategoryFolder(props) {
let css_class = '';
let id = Number.parseInt(props.key) + 1;
if (id % 3 == 0)css_class = 'tert-tag';
else if (id % 3 == 2) css_class = 'even-tag';
return (
<div class="gwd-div-7ybz" name="folder-container">
<div class={"gwd-div-qb7z " + css_class} name="folder-tag-container">
<fieldset class="gwd-fieldset-poz5" name="folder-tag-text"><h1 class='category-title'>{props.CategoryTitle}</h1></fieldset>
</div>
<svg data-gwd-shape="rectangle" class="gwd-rect-c8gx" name="folder-recipe-body"></svg>
</div>
)
}
When I debug all this, the root element is identified and I can see the ajax function succeeding and the render function of Container running. But, for whatever reason, the root element remains untouched as <div id="root"></div> without ever being modified.
Thanks in advance!
Update: I should mention that the console shows no errors at all!
Update 2: The files posted are .jsx while the ones included in index.html are transpiled with npx babel --watch modules/src --out-dir public/modules --presets react-app/prod

You don't return <CategoryFolder style={{'z-index':i,top:i*SPACING+'%'}} CategoryTitle={category}></CategoryFolder> in map() function

Related

Call eel object with TypeScript

I want to call a function using eel that isn't available before the program runs.
With plain JS it works just fine, I need some workaround or something similar for TS.
Python file
import eel
eel.init('web', allowed_extensions=['.js', '.html'])
#eel.expose
def my_python_function():
print(2)
eel.start('index.html', mode='chrome', cmdline_args=['--kiosk'])
Html
<!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>
<button id="myButton"></button>
<script type="text/javascript" src="/eel.js"></script>
<script type="module" src="js/index.js"></script>
</body>
</html>
Working JS
let button = document.getElementById("myButton");
button.onclick = buttonClicked;
function buttonClicked()
{
console.log("Clicked");
eel.my_python_function();
}
If I am not using TS in it's intended way I'm sorry, I'm a beginner in web dev.
The following code is what i tried in TS but didn't work
let button : HTMLElement | null= document.getElementById('myButton');
button?.addEventListener("click", buttonClicked)
function buttonClicked()
{
console.log("Clicked");
eel.my_python_function(); // Error here
}
I got it working by ignoring the error.
let button : HTMLElement | null= document.getElementById('myButton');
button?.addEventListener("click", buttonClicked)
function buttonClicked()
{
console.log("Clicked");
// #ts-ignore
eel.my_python_function();
}

Importing RxJs in small Javascript project

I'm trying to import RxJs in a small javascript project using "import" in my script file but I keep on getting the following error:
Subscriber.js:10 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'rxjs')
This is what my html file looks like:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./styles/style.css">
<title>Load RxJs using import</title>
</head>
<body>
<h1>Importing RxJs Lib</h1>
<div>
<h1 id="info">'loading ...'</h1>
</div>
<!-- <script src="https://unpkg.com/rxjs#7.5.7/dist/bundles/rxjs.umd.js"></script> -->
<script src="./js/script.js"></script>
</body>
</html>
The script file looks like this:
// const updateUI = text => document.querySelectorAll('#info')[0].innerText = "finished";
const loadRxJsLib = async () => {
await import('https://unpkg.com/rxjs#7.5.7/dist/bundles/rxjs.umd.js');
}
document.addEventListener('DOMContentLoaded', (event) => {
loadRxJsLib();
});
document.addEventListener('readystatechange', (event) => {
if (document.readyState === 'complete') {
const { range } = rxjs;
const { filter, map } = rxjs.operators;
range(1, 200)
.pipe(
filter((x) => x % 2 === 1),
map((x) => x + x)
)
.subscribe((x) => console.log(x))
}
});
Any idea why it's not working? any comment will be highly appreciated
After researching a little bit more, I found out that it might be related to the CDN. I have tried the skypack CDN with the following URL
https://cdn.skypack.dev/pin/rxjs#v7.5.7-j3yWv9lQY9gNeD9CyX5Y/mode=imports/optimized/rxjs.js
...and I did not get the error anymore

Javascript Korean Encoding Issue - How do i resolve github pages image 404 async error

I'm trying to realize that when I press my photo, it changes to an angel photo, and when I press celebrity photo, it changes to a ghost photo.
In VSCode, it's good when you look at copy path, but it's image (async) 404 error just by posting it on GitHub pages. Help me. Because of this, the commit is already 40.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>친구들을 위한 사이트</title>
<link rel="stylesheet" href="style.css" />
<link href="https://fonts.googleapis.com/css2?family=Gugi&display=swap" rel="stylesheet">
</head>
<body>
<h1>투표부탁해!!</h1>
<div class="container">
<div class="comment">누가 더 잘생겼나요?! 정답을 맞추면 선물이 와르르!</div>
<img src="images/제혁.png" class="image-jehyuk" onclick="changeImage()"></img>
<span>송제혁</span>
<img src="images/고수.png" class="image-gosu" onclick="changeImage2()"></img>
<span>고수</span>
</div>
<script src="index.js" defer></script>
</body>
</html>
const jehyuk = document.querySelector(".image-jehyuk");
const gosu = document.querySelector(".image-gosu");
const mainTitle = document.querySelector("h1");
const subTitle = document.querySelector(".comment");
function makeSound() {
let gosupick = new Audio("sounds/비명.mp3");
gosupick.play();
}
function thanksText() {
mainTitle.innerHTML = "감사합니다ㅎㅎ";
subTitle.innerHTML = "감사합니다ㅎㅎ";
}
function badText() {
mainTitle.innerHTML = "벌이닷!";
subTitle.innerHTML = "벌이닷!";
}
function changeImage() {
if (jehyuk.getAttribute("src") === "images/제혁.png") {
jehyuk.setAttribute("src", "images/제혁픽.png");
jehyuk.classList.add("bigger");
thanksText();
} else {
jehyuk.setAttribute("src", "images/제혁.png");
}
}
function changeImage2() {
if (gosu.getAttribute("src") === "images/고수.png") {
gosu.setAttribute("src", "images/고수픽.png");
gosu.classList.add("bigger");
badText();
} else {
gosu.setAttribute("src", "images/고수.png");
}
}
Answer
Hello, 제혁! Way I see it's just korea language encoding error
If you check "고수" === "고수" you can get false because of it is write difference encoding type (Maybe utf-8 and utf-16) So, you need to normalize your text
Korean Answer
한국어가 같게 보이는데 Javascript 특성상 인코딩 타입에 따라 글자는 같게 보이나, 서로 다른 글자로 인식하는 경우가 Mac OS(경험상) 있습니다.
콘솔로 테스트 해 본 결과 바이너리 데이터로는 "제혁픽" === "제혁픽"이 false로 나와서 없는 데이터라고 나오고 있습니다. 보통 이 문제를 해결하기 위해 String 타입에 normalize()라는 메소드를 쓸 수 있습니다.
I ask for stack overflow user's patience. I'm so sorry using our own language but it is problem about korean language encoding type.
Reference Image

Why does this HTTP request return array lengths rather than content?

I am working on some stuff here that includes fetching data asynchronously from an API. All is well except when I try pushing the correct answer into the incorrect answers array. All that is being returned are the respective array lengths rather than the content. What is it that I am doing wrong?
Here are the HTML and jQuery codes:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<h3>Answers</h3>
<ol></ol>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</body>
</html>
jQuery
$(() => {
$.ajax({
method: "GET",
url: "https://opentdb.com/api.php?amount=50&category=18",
async: true,
success: (data) => {
let results = data.results;
$.each(results, (i, difficulty, question) => {
difficulty = results[i].difficulty;
question = results[i].question;
correctAnswer = results[i].correct_answer;
answers = results[i].incorrect_answers;
$("ol").append(`
<li>${answers.push(correctAnswer)}</li>
`);
});
}
});
});
Check the docs for the push function.
Return value
The new length property of the object upon which the method was called.
Aat the end of your function you are pushing the correctAnswer to answers which returns the length of answers array and you are showing that in your html. That's perfectly natural.
Push first and then create the html tag.
Check this;
$(() => {
$.ajax({
method: "GET",
url: "https://opentdb.com/api.php?amount=50&category=18",
async: true,
success: (data) => {
let results = data.results;
$.each(results, (i, difficulty, question) => {
difficulty = results[i].difficulty;
question = results[i].question;
correctAnswer = results[i].correct_answer;
answers = results[i].incorrect_answers;
answers.push(correctAnswer)
$("ol").append(`
<li>${correctAnswer}</li>
`);
});
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<h3>Answers</h3>
<ol></ol>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</body>
</html>

Component undefined in ReactJS

I'm playing around with ReactJS. I have defined three components, which are nested:
UserProfile.jsx
var React = require('react');
var UserProfile = React.createClass({
getInitialState: function() {
return {
username: "zuck"
};
},
render: function() {
return (
<UserProfile>
<ProfileImage username={this.props.username}/>
<ProfileLink username={this.props.username}/>
</UserProfile>
);
}
});
React.render(<UserProfile username="zuck"/>, document.body);
module.exports = UserProfile;
ProfileLink.jsx
var React = require('react');
var ProfileLink = React.createClass({
render: function() {
return (
{this.props.username}
);
}
});
module.exports = ProfileLink;
ProfileImage.jsx
var React = require('react');
var ProfileImage = React.createClass({
render: function() {
return (
<img src="//graph.facebook.com/{this.props.username}/picture"/>
);
}
});
module.exports = ProfileImage;
My html file basically only includes the three jsx files (btw, is there a way to bundle all these into a single request during development?)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React FB Link</title>
</head>
<body>
<script type="text/javascript" src="UserProfile.jsx"></script>
<script type="text/javascript" src="ProfileLink.jsx"></script>
<script type="text/javascript" src="ProfileImage.jsx"></script>
</body>
</html>
I'm using beefy to handle and serve the JSX files, using beefy *.jsx 8000 -- -t reactify.
The resulting files are (in truncated form):
UserProfile.jsx
ProfileLink.jsx
ProfileImage.jsx
Loading the html page results in an error:
Uncaught ReferenceError: ProfileImage is not defined
with reference to line 15 in UserProfile.jsx:
React.createElement(ProfileImage, {username: this.props.username}),
You might need to load ProfileImage.jsx and ProfileLink.jsx before your UserProfile.jsx since right now the page is parsing Userprofile.jsx first and it doesn't know what ProfileImage mean (because you haven't loaded it yet)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React FB Link</title>
</head>
<body>
<script type="text/javascript" src="ProfileLink.jsx"></script>
<script type="text/javascript" src="ProfileImage.jsx"></script>
<script type="text/javascript" src="UserProfile.jsx"></script>
</body>
</html>
You can use any module bundler to bundle up your files (Browserify, Gulp, Webpack) into one single file as entry point

Categories