In my project, I am trying to tie together Django and React.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" /> {% load static %}
<link rel="icon" href="{% static 'logofavicon.ico' %}" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta property="og:image" content="{% static 'Banner.png' %}">
<meta name="description" content="The future of digital content" />
<link rel="apple-touch-icon" href="{% static 'logo192.png' %}" />
<link rel="manifest" href="{% static 'manifest.json' %}" />
<title>Drop Party</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<script type="module" src="{% static 'index.js' %}"></script>
<div id="root"></div>
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./styleguide.css";
import "./globals.css";
ReactDOM.render( <
React.StrictMode >
<
App / >
<
/React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/frontend/'
STATICFILES_DIRS = (
FRONTEND_DIR / 'build', FRONTEND_DIR / 'src', FRONTEND_DIR / 'public'
)
Project Hierarchy
I have looked at this post, and confirmed that this solution is not applicable for me.
The primary issue, I think, is that Django is serving the html, but not running the .js, so I'm unsure of where to go with this.
I have also confirmed that the image linking is working as well, so I'm not getting 404 errors or anything like that.
Secondary, semi-related question: Should I be linking the favicons like this? I get the feeling I shouldn't be serving the html statically, but I was unable to find how exactly to serve the project, other than serving the html statically.
(edit) I have added in the script as in comments, but now I get an error where Django seems to reject the React tags.
Your HTML file has no <script> tag for your index.js (although, interestingly, it does have a <noscript>).
You need to tell your page about every JS file you want to run, which you do by using <script> tags.
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script for more info.
Get index.js in the public folder.
Add the line below after body tag,
<script src="index.js"></script>
Related
I am trying to display a simple form using react but I get the error "Target container is not a DOM element" despite the fact that the root element is definitely a DOM element as I have check using console.
edit : Importing form 'react-dom' and using 'render' works fine but I cannot seem to get it work other wise
Here is the form component
import React from 'react';
export default function StudentForm()
{
return (
<form>
//some stuff
</form>
)
}
My index file
import ReactDOM from 'react-dom/client';
import './index.css';
import StudentForm from './App';
const root = document.getElementById('root');
ReactDOM.createRoot(<StudentForm/>,root);
Here is my index.html file
<!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>
</body>
</html>
I guess you don't have a element with id root in your index.html, please add the following tag in your index.html,
<div id="root" />
try this:
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<React.StrictMode>
<StudentForm />
</React.StrictMode>
)
You need to add your main or index script to HTML.
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
I am trying to integrate Bitmovin player to my react js application. I am new to react js. I have included the cdn link to the index.html file. when the video banner is clicked a new page should open with the video player. So in App.js I have created a route to a compnent called VideoPlayer.js where I have placed the <div> element where the video player will be integrated. I have placed the javascript codes of the video player in the index.html page.
Am I doing it right because the video player is not showing and when I place the javascript code of the video player to the component it couldn't find the bimovin and Player.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags 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`.
-->
<link
rel="stylesheet"
href="%PUBLIC_URL%/assets/bootstrap/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="%PUBLIC_URL%/assets/css/style.css" />
<link rel="stylesheet" href="%PUBLIC_URL%/assets/css/responsive.css" />
<link rel="stylesheet" href="%PUBLIC_URL%/assets/slick/slick.css" />
<link rel="stylesheet" href="%PUBLIC_URL%/assets/slick/slick-theme.css" />
<link
rel="stylesheet"
type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/material-design-icons/3.0.1/iconfont/material-icons.min.css"
/>
<script
defer
src="%PUBLIC_URL%/assets/fontawesome/svg-with-js/js/fontawesome-all.js"
></script>
<script src="https://cdn.bitmovin.com/player/web/8/bitmovinplayer.js" type="text/javascript"></script>
<script src="https://js.stripe.com/v3/"></script>
<span id="header_scripts"></span>
</head>
<body>
<div id="root"></div>
<div id="google_analytics"></div>
<div id="body_scripts"></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` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script src="%PUBLIC_URL%/assets/js/jquery.min.js"></script>
<script src="%PUBLIC_URL%/assets/js/popper.min.js"></script>
<script src="%PUBLIC_URL%/assets/bootstrap/js/bootstrap.min.js"></script>
<script src="%PUBLIC_URL%/assets/js/script.js"></script>
<script src="%PUBLIC_URL%/assets/jwplayer/jwplayer.js"></script>
<script type="text/javascript">
var bitmovinConfig = {
key: "a9438b8a-97ae-4502-955b-fe615878e8c7",
playback: {
autoplay: true,
muted: true
},
dnaConfig: {},
style: {
width: "",
height: "",
ux: true
}
};
var playerDiv = document.getElementById("demoplayer");
if(playerDiv){
console.log("Success");
player = new bitmovin.player.Player(
document.getElementById("demoplayer"),
bitmovinConfig
);
player
.load({
//Only one playlist URL must be set at a time.
hls: "https://demo-vod.streamroot.io/index.m3u8"
//dash: 'YOUR_PLAYLIST_URL',
//smooth: 'YOUR_PLAYLIST_URL'
})
.then(function() {
player.play();
});
}else{
console.log("No Success");
}
</script>
</body>
</html>
App.js:
import React, { Component } from "react";
import ReactTimeout from "react-timeout";
import Emitter from "./components/Services/EventEmitter";
import { Router, Switch, Route, Redirect } from "react-router-dom";
import { createBrowserHistory as createHistory } from "history";
import VideoComponent from "./components/User/Video/VideoPlayer";
<AppRoute
path={"/video/:id"}
component={VideoComponent}
layout={EmptyLayout}
screenProps={this.eventEmitter}
/>
I have not included all the codes of App.js as the file has a lot of codes and for security reasons.
VideoPlayer.js(Component) :
import React, { useState, useEffect } from 'react';
class VideoComponent extends React.Component {
render() {
return( <div><div id="demoplayer"></div>);
}
}
export default VideoComponent;
Check out these examples here. I don't see the Bitmovin player in your code anywhere...
https://github.com/bitmovin/bitmovin-player-web-samples/tree/main/react
In a Gatsby.js project, is there any way to inject raw html inside the <head></head> tag of every page? I'm receiving a string of html for tracking (inline and external script tags, link tags and meta tags) that I just need to dump into the head tag.
Edit: Here is an example of what the html looks like that I'll receive (due to restrictions of the environment I'm working in, I'm not able to edit the html string):
<script src="//sometracking.com/script.js" async></script>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','TAGID');</script>
<!-- End Google Tag Manager -->
<link rel="stylesheet" type="text/css" href="https://somefont.com/stylesheet.css" />
<link href="~/another/stylesheet.css" type="text/css" rel="stylesheet" />
<link href="~/more/styles.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="~/vendor/javascript.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="format-detection" content="telephone=no">
<meta name="apple-itunes-app" content="app-id=123456789">
<meta name="google-play-app" content="app-id=com.blah.blah">
<link rel="apple-touch-icon" sizes="180x180" href="~/icon.png" />
..
I've tried using react-helmet (requires either a: properties passed to the meta prop or b: the script/meta/link tags to be JSX as children)
I've tried using the onPreRenderHTML API within gatsby-ssr.js. (similar problem where it expects jsx instead of a string)
// THIS RENDERS THE HTML AS TEXT IN THE BODY TAG
const headScripts = `<script type="text/javascript">alert("tracking stuff");</script>`;
exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => {
replaceHeadComponents([...getHeadComponents(), headScripts]);
};
Plugins like gatsby-plugin-google-tagmanager are not an option as the tracking html comes in as one big string
Any insight would be greatly appreciated!
I solved this by creating a custom html.js file (Gatsby documentation here) and using html-react-parser.
First I copied .cache/default-html.js to src/html.js in order to modify the root html document that Gatsby uses. Then I used the html-react-parser package to place the tracking html that is given to me into the head.
My modifications to the html.js file are indicated by the ADDED comments below
import React from "react";
import PropTypes from "prop-types";
import parse from "html-react-parser"; // ADDED
import getTrackingHtml = from './myCustomUtils'; // ADDED
export default function HTML(props) {
const trackingHtml = getTrackingHtml(); // ADDED
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{props.headComponents}
{parse(trackingHtml)} {/* ADDED */}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<div
key={"body"}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: props.body }}
/>
{props.postBodyComponents}
</body>
</html>
);
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
};
(Note: "Anything you render in the html.js component will not be made “live” in the client like other components" -Gatsby Documentation)
On going through multiple DOCs I get to know that index.html file is the entry point for a React application and all the components we load overrides this file. But if I am making changes to the index.html file that is not reflected in the web page. I am working on integrating Zoom SDKs which needs to include script tags inside the index.html or else JQuery errors are thrown to the console.
Contents of my public/index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link type="text/css" rel="stylesheet" href="https://source.zoom.us/1.7.0/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="https://source.zoom.us/1.7.0/css/react-select.css" />
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script src="https://source.zoom.us/1.7.2/lib/vendor/react.min.js"></script>
<script src="https://source.zoom.us/1.7.2/lib/vendor/react-dom.min.js"></script>
<script src="https://source.zoom.us/1.7.2/lib/vendor/redux.min.js"></script>
<script src="https://source.zoom.us/1.7.2/lib/vendor/redux-thunk.min.js"></script>
<script src="https://source.zoom.us/1.7.2/lib/vendor/jquery.min.js"></script>
<script src="https://source.zoom.us/1.7.2/lib/vendor/lodash.min.js"></script>
<script src="https://source.zoom.us/zoom-meeting-1.7.2.min.js"></script>
</body>
</html>
My index.js configuration:
import React from 'react';
import ReactDOM from 'react-dom';
import {
Redirect,
HashRouter as Router,
Route,
Switch
} from 'react-router-dom';
import { Provider } from 'react-redux';
import { setStore } from './store/base';
import configureStore from './store/configureStore';
import './App.scss';
import MeetingRoom from './containers/MeetingRoom/MeetingRoom';
export const store = configureStore({});
setStore(store);
const routes = (
<Provider store={store}>
<Router>
<Switch>
<Route component={MeetingRoom} path='/m/:mid/' />
</Switch>
</Router>
</Provider>
);
ReactDOM.render(routes, document.getElementById('root'));
If I am changing the text inside <noscript> tag i.e You need to enable JavaScript to run this app. to some other string but it is not getting reflected in the web page. So how my index.html is getting loaded I cannot figure out. Is there any other information I need to provide for getting the solution?
The HTML noscript element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. Add some string inside div element to see on the webpage
I think I have a problem with a script that doesn't load (or load too early).
I try to implement Stripe library for paiement. For that, I have to include a script before using Stripe functions in my code.
I added the given script src="https://js.stripe.com/v3/", in my public folder, in index.html in the header as follow:
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<script src="https://js.stripe.com/v3/"></script>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
I created an empty app, with only call of Stripe. here is App.js :
import React from 'react';
import './App.css';
import {Button} from 'react-bootstrap'
class App extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
var stripe = Stripe('pk_test_XXXXXXXXXXXX');
// I will use stripe variable later. But for now I have an error with previous line
}
render() {
return(
<div>
<Button
className= "btn-xlBook"
variant="primary"
onClick={this.handleClick}>
OK
</Button>
</div>
)
}
}
export default App
But when I make a yarn start, I have the error 'Stripe' is not defined no-undef.
I don't understand, I call the script in the header, but the behavior is as if the script wasn't loaded yet.
Do you know how to solve it ? I I add a script in the header of index.html, it should load before the app, isn't it ?
You don't import Stripe anywhere. Like you do with Button for example. Check out React Stripe Elements for one example of how to use Stripe in React.
Use npm package of stripe instead and import it. Add the import statement and use the wrapper in your index.js
import {StripeProvider} from 'react-stripe-elements';
<StripeProvider apiKey="pk_test_12345">
<MyStoreCheckout />
</StripeProvider>
and then in your console install the package:
npm install --save react-stripe-elements
or
yarn add react-stripe-elements