How to import from React-Select CDN with React and Babel? - javascript

I've created a react application following the steps on the React Website, but I'm having issues utilizing the React-Select Library (particularly the Select Component).
I can only use cdn files to load dependencies, including the React-Select cdn file located on cdnjs
https://cdnjs.cloudflare.com/ajax/libs/react-select/2.1.2/react-select.js
I'm getting the following error with my react-app:
ReferenceError: Select is not defined[Learn More]
See below for my script and here for my codepen
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/react#15.0.0/dist/react-with-addons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.min.js"></script>
<script src="https://unpkg.com/react-dom#0.14.0/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-select/2.1.2/react-select.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<title>Using React Select CDN</title>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<div>
Test Text
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
</div>
);
}
}
ReactDOM.render(<App/>, document.querySelector("#root"))
</script>
</body>
</html>
I've also tried the following which throws the same error
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/react#15.0.0/dist/react-with-addons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.min.js"></script>
<script src="https://unpkg.com/react-dom#0.14.0/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-select/2.1.2/react-select.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-select/2.1.2/react-select.js"></script>
<title>Using React Select CDN</title>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
require(['react-select'])
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<div>
Test Text
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
</div>
);
}
}
ReactDOM.render(<App/>, document.querySelector("#root"))
</script>
</body>
</html>
How can I get React-Select to work? Perhaps

It looks for the latest react-select you need to add the latest dependencies -
Codepen
<script src="https://unpkg.com/react#16.7.0/umd/react.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/emotion#9.2.12/dist/emotion.umd.min.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/prop-types#15.5.10/prop-types.min.js"></script>
<script src="https://unpkg.com/react-input-autosize#2.2.1/dist/react-input-autosize.min.js"></script>
<script src="https://unpkg.com/react-select#2.1.2/dist/react-select.min.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>

Related

How to use JS Fiddle for rending React select

I want to render third party library react-select in JS Fiddle. I have added libraries in jsfiddle but not sure how to use Select component from react-select. I am getting "Error Select is not defined".
https://jsfiddle.net/7nydx09p/1/
const App = () => {
return <div> Test
<Select />
</div>
}
ReactDOM.render(<App/>, document.getElementById('root'));
look here : https://jsfiddle.net/zh4593oL/1/
look here for the issue : https://github.com/JedWatson/react-select/issues/4120
html
<div id="root"></div>
<script type="module">
import Select from 'https://cdn.pika.dev/react-select#^3.1.0';
window.Select = Select;
</script>
js
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
const App = () => {
return <div> <Select options={options} /> </div>
}
ReactDOM.render(<App/>, document.getElementById('root'));

parse json in a vue-treeselect component

In a https://vue-treeselect.js.org/ component, how can I load json? My code is not working
<html>
<head>
<!-- include Vue 2.x -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue#^2"></script>
<!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
<script src="https://cdn.jsdelivr.net/npm/#riophae/vue-treeselect#^0.4.0/dist/vue-treeselect.umd.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#riophae/vue-treeselect#^0.4.0/dist/vue-treeselect.min.css">
</head>
<body>
<div id="app">
<treeselect v-model="value" :multiple="true" :options="options" />
</div>
</body>
<script>
// register the component
Vue.component('treeselect', VueTreeselect.Treeselect)
var tree = new Vue({
el: '#app',
data: {
// define the default value
value: null,
// define options
options: function () {
return JSON.parse(this.json);
}
},
})
$.getJSON("my.json", function (json) {
tree.json = json;
});
</script>
</html>
Put the following code inside the mounted hook :
let vm = this;
$.getJSON("https://jsonplaceholder.typicode.com/users", function(json) {
vm.options = json;
});
you should update the options property directly in the callback of ajax request.
<html>
<head>
<!-- include Vue 2.x -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
<script src="https://cdn.jsdelivr.net/npm/#riophae/vue-treeselect#^0.4.0/dist/vue-treeselect.umd.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#riophae/vue-treeselect#^0.4.0/dist/vue-treeselect.min.css">
</head>
<body>
<div id="app">
<treeselect v-model="value" :multiple="true" :options="options" />
</div>
</body>
<script>
// register the component
Vue.component('treeselect', VueTreeselect.Treeselect)
var tree = new Vue({
el: '#app',
data: {
// define the default value
value: null,
// define options
options: []
},
mounted() {
let vm = this;
$.getJSON("https://jsonplaceholder.typicode.com/users", function(json) {
vm.options = json;
});
}
})
</script>
</html>

Next.js and Webpack inline Javascript or CSS ressources

I have the following use case: I need to generate static files with React and Next.js. For that I extended the next.config.js with the following content:
module.exports = {
exportTrailingSlash: true,
exportPathMap: async function () {
const paths = {
'/': { page: '/' }
}
const errorPages = [
{ id: 1, name: '404', lang: 'en' },
{ id: 2, name: '500', lang: 'en' }
]
errorPages.forEach(errorPage => {
paths[`/errorPage/${errorPage.id}`] = {
page: '/errorPage/[id]',
query: { id: errorPage.id }
}
})
return paths
},
}
This totally works. The files are beeing generated in the out folder after npm export
An additional use case however is this one:
The index.html file needs to work everywhere, not just in the exact place it has in the out folder. For example another webapp queries an API which scans the index.html and returns the html as string from that file. This html string has to work, but the references for the js files/bundles are relative (see link and script tags):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1"
/>
<meta name="next-head-count" content="2" />
<link
rel="preload"
href="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/index.js"
as="script"
/>
<link
rel="preload"
href="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/_app.js"
as="script"
/>
<link
rel="preload"
href="/_next/static/runtime/webpack-91b117697e716c22a78b.js"
as="script"
/>
<link
rel="preload"
href="/_next/static/chunks/framework.94bc9fd9a7de53a90996.js"
as="script"
/>
<link
rel="preload"
href="/_next/static/chunks/commons.6419ced117edf62014da.js"
as="script"
/>
<link
rel="preload"
href="/_next/static/runtime/main-2ba45c6c0e61dfa5f796.js"
as="script"
/>
</head>
<body>
<div id="__next">
<div style="margin:20px;padding:20px;border:1px solid #DDD">
<h1>Error Pages</h1>
<ul>
<li>test a</li>
<li>test 2</li>
</ul>
</div>
</div>
<script
nomodule=""
src="/_next/static/runtime/polyfills-2889d9d9fcf08314dd3a.js"
></script>
<script
async=""
data-next-page="/"
src="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/index.js"
></script>
<script
async=""
data-next-page="/_app"
src="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/_app.js"
></script>
<script
src="/_next/static/runtime/webpack-91b117697e716c22a78b.js"
async=""
></script>
<script
src="/_next/static/chunks/framework.94bc9fd9a7de53a90996.js"
async=""
></script>
<script
src="/_next/static/chunks/commons.6419ced117edf62014da.js"
async=""
></script>
<script
src="/_next/static/runtime/main-2ba45c6c0e61dfa5f796.js"
async=""
></script>
<script
src="/_next/static/UkokJ2QynwMCza2ya8Vuz/_buildManifest.js"
async=""
></script>
</body>
</html>
Is there a way to tell next to include this js files inline?
What I tried:
I am trying to use HtmlWebpackPlugin and HtmlWebpackInlineSourcePlugin and updated next.config.js like this:
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin')
module.exports = {
exportTrailingSlash: true,
exportPathMap: async function () {
const paths = {
'/': { page: '/' }
}
const errorPages = [
{ id: 1, name: '404', lang: 'en' },
{ id: 2, name: '500', lang: 'en' }
]
errorPages.forEach(errorPage => {
paths[`/errorPage/${errorPage.id}`] = {
page: '/errorPage/[id]',
query: { id: errorPage.id }
}
})
return paths
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
config.plugins.push(
new HtmlWebpackPlugin({
inlineSource: '.(js|css)$' // embed all javascript and css inline
})
)
config.plugins.push(new HtmlWebpackInlineSourcePlugin())
return config
}
}
it doesn't transform the resources into the inline format and keeps linking them. Is there a way to achieve the desired result with any other webpack addition or is the config wrong?
thanks in advance!
EDIT: this is my project.json dependency section:
"dependencies": {
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"html-webpack-inline-source-plugin": "0.0.10",
"html-webpack-plugin": "^3.2.0"
}
What I ended up doing is using a StaticDocument instead of the default Document (when in the production environment). Then my StaticDocument is used with CustomHead during export. In there, all link preloads are removed. Like this, no link tag will be rendered in the <head> of the final exported HTML page.
~/pages/_document.js
import Document, { Main, Head } from 'next/document'
class CustomHead extends Head {
render () {
const res = super.render()
function transform (node) {
// remove all link preloads
if (
node &&
node.type === 'link' &&
node.props &&
node.props.rel === 'preload'
) {
return null
}
if (node && node.props && node.props.children) {
return {
...node,
props: {
...node.props,
children: Array.isArray(node.props.children)
? node.props.children.map(transform)
: transform(node.props.children)
}
}
}
if (Array.isArray(node)) {
return node.map(transform)
}
return node
}
return transform(res)
}
}
class StaticDocument extends Document {
render () {
return (
<html>
<CustomHead />
<body>
<Main />
</body>
</html>
)
}
}
export default process.env.NODE_ENV === 'production'
? StaticDocument
: Document

How can I run all the scripts from only one script? (HTML with React.js)

Can't use Node.js, jsx, any extension or server, or any other thing (rule at work).
I have an HTML file with three scripts using React.js, this is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<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/babel-standalone#6.15.0/babel.min.js" crossorigin></script>
<title>HTML with multiple React.js scripts</title>
</head>
<body>
<p>HTML with multiple scripts using React.js... without Node.js, jsx or any other thing</p>
<div>
<div id="divComponent1"></div>
<div id="divComponent2"></div>
<div id="divComponent3"></div>
</div>
<script src="component1.js"></script>
<script src="component2.js"></script>
<script src="component3.js"></script>
</body>
</html>
component1.js:
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'This is the first React.js component.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Component number one!'
);
}
}
const domContainer = document.querySelector('#divComponent1');
ReactDOM.render(e(LikeButton), domContainer);
component2.js:
'use strict';
const list =
React.createElement('div', {},
React.createElement('h1', {}, 'Component number two'),
React.createElement('ul', {},
[
React.createElement('li', {}, 'Without Node.js'),
React.createElement('li', {}, 'Without jsx'),
React.createElement('li', {}, 'Without any server')
]
)
);
const divComponent2 = document.querySelector('#divComponent2');
ReactDOM.render(list, divComponent2);
component3.js:
var x = "Johnny B. Goode (Component three)";
class JohnnyBGoode extends React.Component {
render() {
return React.createElement('div', {},
React.createElement("h1", {}, x),
React.createElement("audio", { id: "woof", controls: "controls", src: "johnny.mp3"}),
);
}
}
const divComponent3 = document.querySelector('#divComponent3');
ReactDOM.render(
React.createElement(JohnnyBGoode, {}, null),
document.getElementById('divComponent3')
);
So, I want to add only one script in the HTML file, and run/render all the others scripts/components from there, something like that:
<script src="index.js"></script>
How can I achieve this? Remember, can't use Node or any other thing.

React can't find 3rd party scripts I've included

I'm trying to work through the React Tutorial and have run into a stumbling block. I have the following HTML
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="./src/favicon.ico" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css" />
<script src="https://npmcdn.com/react#15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.1/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
<script src="https://npmcdn.com/jquery#3.1.0/dist/jquery.min.js"></script>
<script src="https://npmcdn.com/remarkable#1.6.2/dist/remarkable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>
<script type="text/babel" src="src/index.js"></script>
<title>React App</title>
</head>
<body>
<div class="container">
<div class="row">
<div id="sidebar" class="col s3">
</div>
<div id="content" class="col s9">
</div>
</div>
</div>
<script type="text/babel">
</script>
</body>
</html>
With the following javascript file.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
var data = [
{ id: 1, author: "Pete Hunt", text: "This is the 1st comment" },
{ id: 2, author: "Jordan Walke", text: "This is *the 3rd* comment." },
{ id: 3, author: "John Doe", text: "This comment is stupid." }
];
var CommentBox = React.createClass({
getInitialState: function() {
return { data: [] };
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({ data: data });
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
render: function() {
return (
<div className="commentForm">
I'm a Form.
</div>
);
}
});
var Comment = React.createClass({
rawMarkup: function() {
var markdown = new Remarkable();
var rawMarkup = markdown.render(this.props.children.toString());
return { __html: rawMarkup };
},
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
});
ReactDOM.render(
<CommentBox data={data} />,
document.getElementById('content')
);
I'm using the content created from the Create React App NPM module. When I run the app, I'm told:
Remarkable isn't defined
$ is not defined
Both JQuery and Remarkable are included in my HTML file, and I made sure to put them before my index.js script. Why is it that the app can't find the Types? Is this a React issue, or a Node,js issue? I'm a bit new to web-dev so I'm not sure which component is at fault here or what i'm doing wrong.
Seems like your scripts are loading asynchronously. Waiting for all your scripts to be loadded with jQuery...
(function($){$(function(){
// your react app code here...
})})(jQuery);

Categories

Resources