react-json-schema tutorial does not show up in browser - javascript

I am completely new to web development (html/js) but would now like to use the react-json-schema package which works great in the provided sandbox.
However, I can't even get the tutorial to work. I have written an html, as given in the tutorial:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<script type="text/jsx" src="react.js"></script>
</body>
</html>
the corresponding javascript file "react.js":
const Form = JSONSchemaForm.default;
const schema = {
title: "Test form",
type: "string"
};
ReactDOM.render((
<Form schema={schema} />
), document.getElementById("app"));
However, the schema simply does not show up in a browser when opening the html. There is no error message.
Things I have tried:
1.) importing the scripts from the cdn, so adding these lines in the html head:
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/#rjsf/core/dist/react-jsonschema-form.js"></script>
2.) re-installing npm and the react-json-schema, react and react-dom packages both locally and globally
3.) importing said packages in the js:
import react from React
import import ReactDOM from 'react-dom'
import Form from "#rjsf/core";

try below:
import Form from 'react-jsonschema-form';
class Index extends DataComponent{
constructor(props){
super(props);
this.state={
schema: {
type: 'object',
title: 'Info',
properties: {
task: {
type: 'string',
title: 'First Name'
}
}
}
}
}
render(){
return(
<Form
schema={this.state.schema}
/>
)
}
}

If you have installed the library then remove
//const Form = JSONSchemaForm.default;

Related

How can I convert class component into functional component when adding React library to a Website?

I want to use react component in html file. It is for micro frontend. So I follow this react official doc for Add React to a Website.
The sample code is as below:
index.html
<html>
<body>
<p>
This is the first like.
<div class="like_button_container" data-commentid="1"></div>
</p>
<p>
This is the second like.
<div class="like_button_container" data-commentid="2"></div>
</p>
<p>
This is the third like.
<div class="like_button_container" data-commentid="text"></div>
</p>
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="like_button.js"></script>
</body>
</html>
like_button.js
"use strict";
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
return e(
"button",
{
onClick: () =>
this.setState((prevState) => ({
liked: !prevState.liked,
})),
},
this.state.liked ? "Liked " + this.props.commentID : "Unliked"
);
}
}
document.querySelectorAll(".like_button_container").forEach((domContainer) => {
const commentID = domContainer.dataset.commentid;
ReactDOM.render(e(LikeButton, { commentID: commentID }), domContainer);
});
Above code is working fine but I want to convert like_button.js, which is class component into functional component.
Thanks in advance.
You need to use babel standalone script to transcompile the code, and you need to include the script for react and react-dom, use these will work.
<html>
<head>
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/#babel/standalone#7.15.7/babel.min.js"></script>
</head>
<body>
<div id="react-container"></div>
<script type="text/babel">
const App = () => <div>Hello!</div>
ReactDOM.render(
<App />, document.getElementById('react-container'))
</script>
</body>
</html>
Babel Standalone converts ECMAScript 2015+ into the compatible version of JavaScript for your browser, CDN usage is described in official documentation, check babel standalone section: Babel Standalone

Use a vanilla JavaScript package in React app

I am aiming to use a Vanilla JavaScript package in a more sophisticated React app to build additional logic around the JavaScript package.
The JavaScript library is LabelStudio and docs can be found here: https://github.com/heartexlabs/label-studio-frontend
However, when I try to import the LabelStudio I get an error saying Module not found: Can't resolve 'label-studio' , as described here https://github.com/heartexlabs/label-studio-frontend/issues/55
Since my understanding of frontend code is limited, I am not sure whether this is something the developers did not expected users to do and just wanted them to use the entire library and customized instead of using the library as a component. My idea was to use the library as in the vanilla javascript example here:
<!-- Include Label Studio stylesheet -->
<link href="https://unpkg.com/label-studio#0.7.1/build/static/css/main.0a1ce8ac.css" rel="stylesheet">
<!-- Create the Label Studio container -->
<div id="label-studio"></div>
<!-- Include the Label Studio library -->
<script src="https://unpkg.com/label-studio#0.7.1/build/static/js/main.3ee35cc9.js"></script>
<!-- Initialize Label Studio -->
<script>
var labelStudio = new LabelStudio('label-studio', {
config: `
<View>
<Image name="img" value="$image"></Image>
<RectangleLabels name="tag" toName="img">
<Label value="Hello"></Label>
<Label value="World"></Label>
</RectangleLabels>
</View>
`,
interfaces: [
"panel",
"update",
"controls",
"side-column",
"completions:menu",
"completions:add-new",
"completions:delete",
"predictions:menu",
],
user: {
pk: 1,
firstName: "James",
lastName: "Dean"
},
task: {
completions: [],
predictions: [],
id: 1,
data: {
image: "https://htx-misc.s3.amazonaws.com/opensource/label-studio/examples/images/nick-owuor-astro-nic-visuals-wDifg5xc9Z4-unsplash.jpg"
}
},
onLabelStudioLoad: function(LS) {
var c = LS.completionStore.addCompletion({
userGenerate: true
});
LS.completionStore.selectCompletion(c.id);
}
});
</script>
How can I make use of the above code in a React Component to facilitate dynamic data loading and use of state to customize the functions?
I don't have a solution making the npm module label-studio to work. I tried importing the dist file instead, but it errors
Expected an assignment or function call and instead saw an expression
So here's a workaround until the maintainers address this.
Copy the JS file from build/static/js, then place it in a script in the public folder on 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="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="%Your_Path_To_Label-Studio%/main.js"></script>
</body>
</html>
The script file defines a global function variable, so you can access it in React by using the window object. The useEffect hook is to make sure the initialization is only run once.
import React, { useEffect, useRef } from "react";
function App() {
const LabelStudio = window.LabelStudio; // label-studio script stores the api globally, similar to how jQuery does
const myLabelStudioRef = useRef(null); // store it and then pass it other components
useEffect(() => {
myLabelStudioRef.current = new LabelStudio("label-studio", {
config: `
<View>
<Image name="img" value="$image"></Image>
<RectangleLabels name="tag" toName="img">
<Label value="Hello"></Label>
<Label value="World"></Label>
</RectangleLabels>
</View>
`,
interfaces: [
"panel",
"update",
"controls",
"side-column",
"completions:menu",
"completions:add-new",
"completions:delete",
"predictions:menu",
],
user: {
pk: 1,
firstName: "James",
lastName: "Dean",
},
task: {
completions: [],
predictions: [],
id: 1,
data: {
image:
"https://htx-misc.s3.amazonaws.com/opensource/label-studio/examples/images/nick-owuor-astro-nic-visuals-wDifg5xc9Z4-unsplash.jpg",
},
},
onLabelStudioLoad: function (LS) {
var c = LS.completionStore.addCompletion({
userGenerate: true,
});
LS.completionStore.selectCompletion(c.id);
},
});
}, []);
return (
<div className="App">
{/* Use Label Studio container */}
<div id="label-studio"></div>
</div>
);
}
export default App;
As far as storing the new instance of LabelStudio, there's many ways to go about it. You can store it as variable on the root component using either useState or useRef hooks and then pass it to child components. If you want to avoid manually passing variable down the component tree, then you need a state manager such as React Context or Redux.
This is the basic setup using LabelStudio as a module in a React component.
yarn add #heartexlabs/label-studio
import LabelStudio from '#heartexlabs/label-studio'
import { useEffect } from 'react'
import '#heartexlabs/label-studio/build/static/css/main.css'
const ReactLabelStudio = () => {
useEffect(() => {
new LabelStudio('label-studio', {
config: {...},
interfaces: [...],
user: {...},
task: {...},
onLabelStudioLoad: function(LS) {
const c = LS.annotationStore.addAnnotation({
userGenerate: true,
});
LS.annotationStore.selectAnnotation(c.id);
}
})
}, [])
return <div id="label-studio" />
}
export default ReactLabelStudio

How can i use a jquery/html/css component inside my react page

I have to use a complex and ready to use component developed using jQuery v2.2.4, javascript html and css inside one of my react pages, because its a fairly huge component with lots of features it really doesn't make sense for us to redevelop this inside react and make it reacty.
So my question is how can i use this inside react?
I simply want to render this component in the middle of my page, whats the best way to do this?, i'm a bit new to this and i don't know where to start.
This is the index.html which calls upon the said component, i thought maybe it helps in someway ?
<!DOCTYPE html>
<html>
<haed>
<title>Test</title>
</haed>
<body>
<link href="ol.css" rel="stylesheet" type="text/css" />
<link href="ls.css" rel="stylesheet" type="text/css" />
<script src="jquery.min.js"></script>
<script src="ol.js"></script>
<script src="ls.js"></script>
<script src="wss_map.js"></script>
<div id="map" style="width: 100%; height: 500px;"></div>
<script>
var i = 0;
var mp=$("#map").wssmap({
maps: [
{
name: 'm2',
type: 'osm',
order: 0,
zoomrange: { min: 0, max: 19 },
visible: true,
}
],
onClick:function(point) {
i++;
var options= {
longitude:point.longitude,
latitude:point.latitude,
label:i
}
mp.addMarker(options);
},
zoom:10
});
var marker=mp.addMarker({ longitude: 51.404343, latitude: 35.715298,label:'Testcase'});
</script>
</body>
</html>
Thanks.
Just follow this instructions:
1: install JQuery via npm :
npm install jquery --save
2: import $ from Jquery on top of you react component file:
import $ from 'jquery';
3: now you can call your JQuery component on maybe React componentDidMount()
componentDidMount() {
var mp=$("#map").wssmap({ ... })
}

Why do I need import React statement even if I don't use React explicitly?

I have an React App, following is JavaScript code
import React from 'react';
import ReactDOM from 'react-dom';
const App = function(){
return <div>Hi</div>
}
ReactDOM.render(<App />, document.querySelector('.container'));
And the HTML file is as following.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style/style.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAq06l5RUVfib62IYRQacLc-KAy0XIWAVs"></script>
</head>
<body>
<div class="container"></div>
</body>
<script src="/bundle.js"></script>
</html>
The question I don't understand is that if I remove import React from 'react', it will show error message like below.
Uncaught ReferenceError: React is not defined
But I don't use React in my code explicitly anywhere, why would it show a message like this. Can anyone tell me what's going on under the hood?
UPDATE:
Not exactly the same question with this one, since what I have in my code is just an individual component, not involving any parent component.
Using JSX (<App />) is just a syntatic sugar for React.createElement().
So when your code is transpiled to pure javascript, references to React will appear there, so you need the import for that.
So yes, you're using it, although you don't see it
See what is your code transpiled to here
'use strict';
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var App = function App() {
return React.createElement(
'div',
null,
'Hi'
);
};
_reactDom2.default.render(React.createElement(App, null), document.querySelector('.container'));

JavaScript ReferenceError: $ is not defined

I have an html file that looks like this:
<!DOCTYPE html>
<html>
<head>
<title>AppName</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="container"></div>
<script src="/bundle.js"></script>
</body>
</html>
And I have a javascript file that contains this:
EDIT: included jQuery via npm, and it seems to have worked.
export function getData(arg, callback) {
var $ = require('jQuery'); // This line was added via EDIT above.
$.ajax({
type: "GET",
url: "/get_data",
data: {data: arg},
success: callback
});
}
When I go to my page and execute the function, I eventually get this error:
Uncaught ReferenceError: $ is not defined
at Object.getData (http://localhost:1234/static/bundle.js:21665:6)
Based on the questions/answers I've seen on SOF, it seems like the solution was to include the jquery script in my html file.
Any ideas what I might be doing wrong?
EDIT: As per request, here is my react index.js file. The error is coming from within the searchApi.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/SearchBar';
import * as searchApi from './api/searchApi';
class App extends React.Component {
constructor() {
super();
this.getData = this.getData.bind(this);
this.processData = this.processData.bind(this);
}
getData(data) {
searchApi.getData(data, this.processData);
}
processData(payload) {
console.log(payload);
}
render() {
return (
<div>
<SearchBar getData={this.getData}/>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);

Categories