Can't render button from React in html - html

I have a ready-made site where I need to import a button from react:
<html>
<head>
</head>
<body>
<div id="root"></div>
<script>
ReactDOM.createRoot(<App />, document.getElementById("root"));
</script>
<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>
<!-- Load our React component. -->
<script src="src/App.js"></script>
</body>
</html>
From here:
import './App.css';
import { ConnectButton } from '#rainbow-me/rainbowkit';
function App() {
return (
<div className="App">
<header className="App-header">
<ConnectButton/>
</header>
</div>
);
}
export default App;
index.js +I have already changed the render values ​​to createRoot as well as other related values ​​from Nikki9696 comment.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import '#rainbow-me/rainbowkit/styles.css';
import {
getDefaultWallets,
RainbowKitProvider,
} from '#rainbow-me/rainbowkit';
import { configureChains, createClient, WagmiConfig } from 'wagmi';
import { mainnet, polygon, optimism, arbitrum } from 'wagmi/chains';
import { alchemyProvider } from 'wagmi/providers/alchemy';
import { publicProvider } from 'wagmi/providers/public';
const { chains, provider } = configureChains(
[mainnet, polygon, optimism, arbitrum],
[
alchemyProvider({ apiKey: process.env.ALCHEMY_ID }),
publicProvider()
]
);
const { connectors } = getDefaultWallets({
appName: 'Evefund',
chains
});
const wagmiClient = createClient({
autoConnect: true,
connectors,
provider
})
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<WagmiConfig client={wagmiClient}>
<RainbowKitProvider chains={chains}>
<App />
</RainbowKitProvider>
</WagmiConfig>
</StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:
reportWebVitals();
But its not rendering, what Im doing wrong? (html just a sample)
Thanks.
p.s. ChatGPT says everything should work C:

you need to transpile your jsx into javascript using some tool like babel:
<html>
<head>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
ReactDOM.render(<App />, document.getElementById("root"));
</script>
<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="https://unpkg.com/#babel/standalone#7.8.3/babel.js"></script>
<!-- Load our React component. -->
<script src="src/App.js" type="text/babel"></script>
</body>
</html>
because javascript doesnt understand jsx it only understands functions from react like React.createElement()

Related

vue + pure html component?

how to implement vue-cli calling pure html method?
Please check below as sample file. because I have custom pure html code and facing difficulty converting it to vuejs.
product.vue
<template>
<custombutton #childclick="childclick" />
</template>
<script>
export default {
component: { custombutton },
methods: {
childclick(value) {
console.log(value)
}
}
}
</script>
custombutton.html
<html>
<body>
<button #click="childclick" />
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script>
var App = new Vue({
el: '#app',
data() {
return {
vueMessage: 'testing vue message',
}
},
methods: {
childclick() {
this.$emit('childclick', 'success!')
}
},
});
</script>
</html>
Assuming you want to preserve the possibility to call Vue component from both .html file and .vue files, I would recommend moving your Vue logic from custombutton.html file into a separate custombutton.js file, which will export an object representing Vue component previously defined in HTML. You can then import custombutton.js both in custombutton.html and product.vue.
Example:
custombutton.js:
export default {
name: 'CustomButton',
template: '<div>Hello world!</div>'
}
custombutton.html:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="app"></div>
<script type="module">
import CustomButton from "./custombutton.js"
new Vue({
el: '#app',
components: { CustomButton },
template: '<CustomButton />'
});
</script>
</body>
</html>
product.vue:
<template>
<CustomButton />
</template>
<script>
import CustomButton from "./custombutton.js"
export default {
components: { CustomButton }
}
</script>
Note that:
For custombutton.html to work target browsers should implement ECMAScript modules.
For product.vue to work you should set runtimeCompiler: true in your Vue CLI configuration. (Since the template in custombutton.js is defined as a string runtime compiler needs to be included in the final bundle.)
It is important to find a suitable location for custombutton.js so it can be imported easily using relative paths from both custombutton.html and custombutton.vue files.
Defining the template as a string in custombutton.js can be quite inconvenient, as you have no markup highlighting, however I don't see any workaround for this.
This solution is a bit more cumbersome, but allows template to be written with syntax highlighting into <script> element, which is more convenient than writing template as a string literal into a template property.
custombutton.js:
export default {
name: 'CustomButton',
data: function () {
return { testVar: 125 }
}
}
custombutton.component.html:
The template is now located in #custombutton-template element. "Hello world! 125" should be printed out.
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>
</head>
<body>
<script id="custombutton-template" type="x-template">
<div>Hello world! {{ testVar }}</div>
</script>
<div id="app"></div>
<script type="module">
import CustomButton from "./custombutton.js"
CustomButton.template = "#custombutton-template"
new Vue({
el: '#app',
components: { CustomButton },
template: '<CustomButton />'
});
</script>
</body>
</html>
product.vue: Thanks to Webpack config (see below) we are able to import contents of custombutton.component.html file as a string, parse it and get inner HTML of #custombutton-template element, which is the desired template.
<template>
<CustomButton />
</template>
<script>
import CustomButton from "./custombutton.js"
import CustomButtonComponent from "./custombutton.component.html"
var el = document.createElement("html")
el.innerHTML = CustomButtonComponent
var template = el.querySelector("#custombutton-template").innerHTML
CustomButton.template = template
export default {
components: { CustomButton }
}
</script>
Importing custombutton.component.html file as string is done by non-default Webpack raw-loader, therefore it is necessary to adjust Webpack config:
vue.config.js:
module.exports = {
runtimeCompiler: true,
configureWebpack: {
module: {
rules: [
{
test: /\.component\.html$/,
use: ["raw-loader"]
}
]
}
}
}
package.json:
{
"devDependencies": {
"raw-loader": "^4.0.2"
}
}

How to get data from json using axios in react?

There are two files reactjs.json in which..
{
"642176ece1e7445e99244cec26f4de1f":
["https://ih1.redbubble.net/image.487729686.1469/pp,550x550.jpg",
"https://ik.imagekit.io/PrintOctopus/s/files/1/0006/0158/7777/products/abey_pagal_hai_kya.png?v=1547744758"]
}
and index.html
<!DOCTYPE html>
<html>
<head>
<title>Image Viewer-Static</title>
<!-- <link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
/>
<link
rel="stylesheet prefetch"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="style.css" /> -->
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/babel">
var imageslink;
class FetchDemo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Pictures apikeys="642176ece1e7445e99244cec26f4de1f" />
</div>
);
}
}
class Pictures extends React.Component {
constructor(props) {
super(props);
axios.get('reactjs.json').then(
res => {
console.log(res.data);
imageslink = res.data;
console.log(imageslink);
})
}
render() {
return (
<div>
{imageslink[this.props.apikeys].map(function(name, index){
return <img key={index} src={name} />;
})}
</div>
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById("root")
);
</script>
</body>
</html>
Error:
Actually I want to fetch data from the reactjs.json file into the index.html using ajax in react. I am using axios for this and for react I am using cdn. But I am unable to fetch the data .
I tried to put it in componentDidMount() in FetchDem class but not works so I PASSED IT INTO THE CONSTRUCTOR but still I am unable to access the data.
So my question is how to acess the data from reactjs.json file to index.html?
React documentation recommends using componentDidMount for API calls.
Also when you fetch the data, you have to keep it in the state. Later the data will be available in the render method.
Here's how you have to tune-up you code:
constructor(props) {
super(props);
this.state = { imageslink: null }
}
componentDidMount() {
axios.get('reactjs.json').then( res => {
this.setState({ imageslink: res.data })
})
}
render() {
const { imageslink } = this.state
if (imageslink) {
// Here you can access this.state.imageslink,
// because they will be fetched.
}
}
Here's a generic Axios React example:
class App extends React.Component {
constructor(props) {
super(props)
this.state = { users: [] }
}
componentDidMount() {
axios.get('https://reqres.in/api/users?page=1')
.then(response => this.setState({ users: response.data.data }))
}
renderUsers() {
const { users } = this.state
return users.map( user => (
<div key={user.id}>{user.first_name} {user.last_name}</div>
))
}
render() {
return <div>{ this.renderUsers() }</div>
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>

Client side React componentDidMount not called (without JSX)

I am learning React and following their step by step tutorial but without the use of JSX. I am not very far into the tutorial but I hit a snag. The componentDidMount method is not being called, and so my timer does not update.
Any help would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Test</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<!--<script crossorigin src="assets/react.development.16.4.1.js"></script>-->
<!--<script crossorigin src="assets/react-dom.development.16.4.1.js"></script>-->
</head>
<body>
<div id="root"></div>
<script>
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello World!",
date: new Date(),
}
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
let fragment = React.createElement(React.Fragment, null, [
React.createElement("h1", {key: "message"}, this.state.message),
React.createElement("p", {key: "time"}, this.state.date.toLocaleTimeString())
]);
return fragment;
}
tick() {
this.setState({
date: new Date()
});
}
}
ReactDOM.render(new App().render(), document.getElementById("root"));
</script>
</body>
</html>
I think the problem is there in one place
ReactDOM.render(new App().render(), document.getElementById("root"));
Why this will not work ?
Because render will return chilren of App component not the App itself
. Your children will be mounted first and your App is neverbe rendered
, hence no componentDidMount for App component
the context is not proper. Try using arrrow funciton here
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello World!",
date: new Date(),
}
}
componentDidMount() {
console.log("mounting")
this.timerID = setInterval(
() => {
this.tick()
},
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
let fragment = React.createElement(React.Fragment, null, [
React.createElement("h1", {key: "message"}, this.state.message),
React.createElement("p", {key: "time"}, this.state.date.toLocaleTimeString())
]);
return fragment;
}
tick = () => {
debugger
this.setState({
date: new Date()
});
}
}
ReactDOM.render(React.createElement(App), document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<!--<script crossorigin src="assets/react.development.16.4.1.js"></script>-->
<!--<script crossorigin src="assets/react-dom.development.16.4.1.js"></script>-->
<div id="root"></div>

React JS Accessing JSON as State

I'm completely brand new to React JS and am trying to create an application that will grab JSON data from a pokemon API, which I will then use to display on screen. Right now, I have it set up so that the user has to input the name of the pokemon they are looking for, i.e. pikachu, and when the search button is pressed, the application will make the API call to return the JSON. I've been searching for the past few days, and cannot seem to find anything to work with the way I currently have my code set up. How do I bind the JSON output to a component that I would then be able to display to the user?
Here's the js code (App.js)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Text field value is: ' + this.state.value);
fetch('https://pokeapi.co/api/v2/pokemon/'+this.state.value+'/')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data.name +" "+ data.id);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<input type="text"
placeholder="enter name of pokemon here"
value={this.state.value}
onChange={this.handleChange}
/>
<button type="button" onClick={this.handleSubmit}>Search the Pokedex</button>
</div>
);
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
Screenshot of issue:
http://imgur.com/a/g9H5r
Try this
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
data: {} //filled by fetch data from API
};
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Text field value is: ' + this.state.value);
var _this = this;
fetch('https://pokeapi.co/api/v2/pokemon/'+this.state.value+'/')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data.name +" "+ data.id);
_this.setState({data: data});
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
_this.setState({data: {}});
});
}
render() {
var data = this.state.data;
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<input type="text"
placeholder="enter name of pokemon here"
value={this.state.value}
onChange={this.handleChange.bind(this)}
/>
<button type="button" onClick={this.handleSubmit.bind(this)}>Search the Pokedex</button>
<h3>{data.id}</h3>
<h3>{data.name}</h3>
</div>
);
}
}
ReactDOM.render(App, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>

Dynamically update a stylesheet using dart within a template in a polymer-element

I am dynamically updating my stylesheet as described in this other SO page. In general it works great, but it doesn't for the HTML DOM tags I have within my polymer element template (e.g. I can not change the style of .above-board).
Do you have an idea how could I make it work? Apart from embedding the style changes directly in the HTML for each element instead of using classes. Showing the code below (tried to remove as much non-relevant code as possible):
index.html
<!DOCTYPE html>
<html lang="en">
...
<body>
<div class="main">
<panepond-board class="player1"></panepond-board>
</div>
<script type="application/dart" src="board.dart"></script>
</body>
</html>
component.html
<link rel="import" href="packages/polymer/polymer.html"/>
<polymer-element name="panepond-board">
<template>
<div class="above-board">
<input type="button" value="toggle config" on-click="{{toggleConfig}}" class="update"/><br/>
<label>score: {{totalScore}}</label>
</div>
...
<link rel="stylesheet" href="board.css"/>
</template>
</polymer-element>
<script type="application/dart" src="board.dart"></script>
 board.dart
import 'dart:html';
import 'dart:async';
import 'dart:math';
import 'package:polymer/polymer.dart';
import "package:range/range.dart";
import 'config.dart';
main() {
initPolymer().run(() {
Polymer.onReady.then((_) {
var board1 = querySelector('.player1');
window.onKeyDown.listen( (e) {
board1.actOnKeyDown(new String.fromCharCodes([e.keyCode]));
});
board1.init();
});
});
}
#CustomTag('panepond-board')
class Board extends PolymerElement {
#observable Config config = new Config(6);
Board.created() : super.created();
void init() {
config.loadCSS();
}
config.dart
import 'package:polymer/polymer.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:html';
class Config extends Observable {
num width;
Config(w) : width = w;
void loadCSS() {
StyleElement styleElement = new StyleElement();
document.head.append(styleElement);
CssStyleSheet sheet = styleElement.sheet;
final rule1 = '.above-board { border: 1px solid blue; }';
sheet.insertRule(rule1, sheet.cssRules.length); //this doesn't show any effect
final rule2 = '.main { border: 1px solid red; }';
sheet.insertRule(rule2, sheet.cssRules.length); //this works fine
}
}
If I manually append .above-board{border: 1px solid blue;} on board.css, the rule will work as expected (i.e. it will display the blue border). Otherwise, doing it programmatically (see rule1 above) has no effect.
I think
document.head.append(styleElement);
should be
document.querySelector('panepond-board.player1')
.shadowRoot.append(styleElement);