Loading JSX file from content server asp.net - javascript

I am facing a issue when I am trying to get my JSX file by a content server. The application has a view Test.cshtml and in this calls a jsx file to render the react portion of the UI to the 'content' div.
When I run it locally in the project using the file structure from the solution it works fine.
<div id="content">
#*react renders here*#
</div>`
#section Scripts{
<script src="_linktoReact_/react-0.14.0.js"></script>
<script src="_linktoReact_/react-dom-0.14.0.js"></script>
<script src="~/Scripts/JSX/test.jsx">
</script>
}
But when I try to run from content server to host the files in a central location (which in this case is localhost:8111) it does not work. The file loads into the browser, but the jsx doesnt execute. This will give me an error of "Uncaught SyntaxError: Unexpected token <" which points to the first line of HTML in the jsx file.
<div id="content">
#*react renders here*#
</div>`
#section Scripts{
<script src="_linktoReact_/react-0.14.0.js"></script>
<script src="_linktoReact_/react-dom-0.14.0.js"></script>
<script src="http://localhost:8111/Scripts/JSX/test.jsx">
</script>
}
So I tried adding the type tag to reference jsx, like below. This removed the "uncaught syntax error" but then doesn't give any errors but also doesn't render the react.
<div id="content">
#*react renders here*#
</div>`
#section Scripts{
<script src="_linktoReact_/react-0.14.0.js"></script>
<script src="_linktoReact_/react-dom-0.14.0.js"></script>
<script type="text/jsx" src="http://localhost:8111/Scripts/JSX/test.jsx">
</script>
}
I tried to find the problem a few different ways and have tinkered with solutions around scoping, CORS, maybe even an issue with routing on the server, but not sure what fixes it.
Attempts to fix:
One suggestion was to use window instead of var like
var TestDataTile = React.createClass({
replace with
window.TestDataTile = React.createClass({
But that to is not working. I am using react-0.14.0.js, react-dom-0.14.0.js
Tried to recompile into js file, which rendered as expected in the solution, but still some issues with some of the code in the test.js file in regard to some api calls.
What could be causing the jsx disconnect?
Can anyone guide me towards correct direction?

Related

Integrating React app into a Wicket/wro4j app [duplicate]

I just got started using React, so this is probably a very simple mistake, but here we go. My html code is very simple:
<!-- base.html -->
<html>
<head>
<title>Note Cards</title>
<script src="http://<url>/react-0.11.2.js"></script>
<!-- <script src="http://<url>/JSXTransformer-0.11.2.js"></script> -->
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<script src="{% static "build/react.js" %}"></script>
</head>
<body>
<h1 id="content">Note Cards</h1>
<div class="gotcha"></div>
</body>
</html>
Note that I am using Django's load static files here. (My JavaScript is a bit more complex, so I won't post it all here unless someone requests it.) This is the line with the error:
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
After which I get the 'target container is not a DOM element error' yet it seems that document.getElementById("content") is almost certainly a DOM element.
I looked at this stackoverflow post, but it didn't seem to help in my situation.
Anyone have any idea why I'd be getting that error?
I figured it out!
After reading this blog post I realized that the placement of this line:
<script src="{% static "build/react.js" %}"></script>
was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.
My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn't find the content id, and thus it wasn't a real DOM element.
Also make sure id set in index.html is same as the one you referring to in index.js
index.html:
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
index.js:
ReactDOM.render(<App/>,document.getElementById('root'));
webpack solution
If you got this error while working in React with webpack and HMR.
You need to create template index.html and save it in src folder:
<html>
<body>
<div id="root"></div>
</body>
</html>
Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.
To do that:
plugins: [
new HtmlWebpackPlugin({
title: "Application name",
template: './src/index.html'
})
],
template property will tell webpack how to build index.html file.
Just to give an alternative solution, because it isn't mentioned.
It's perfectly fine to use the HTML attribute defer here. So when loading the DOM, a regular <script> will load when the DOM hits the script. But if we use defer, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end - when the DOM has loaded (source).
<script src="{% static "build/react.js" %}" defer></script>
Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.
I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.
For those that implemented react js in some part of the website and encounter this issue.
Just add a condition to check if the element exist on that page before you render the react component.
<div id="element"></div>
...
const someElement = document.getElementById("element")
if(someElement) {
ReactDOM.render(<Yourcomponent />, someElement)
}
Also you can do something like that:
document.addEventListener("DOMContentLoaded", function(event) {
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
})
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
One of the case I encountered the same error in a simple project. I hope the solution helps someone.
Below code snippets are sufficient to understand the solution :
index.html
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
someFile.js : Notice the line const portalElement = document.getElementById("overlays"); below :
const portalElement = document.getElementById("overlays");
const Modal = (props) => {
return (
<Fragment>
      {ReactDOM.createPortal(<Backdrop />, portalElement)}
      
{ReactDOM.createPortal(
<ModalOverlay>{props.children}</ModalOverlay>,
portalElement
)}
    
</Fragment>
);
};
I didn't have any element with id = "overlays" in my index.html file, so the highlighted line above was outputting null and so React wasn't able to find inside which element it should create the portal i.e {ReactDOM.createPortal(<Backdrop />, portalElement)} so I got below error
I added the div in index.html file and the error was gone.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="overlays"></div>
<div id="root"></div>
</body>
I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added
<div id="root"></div>
just before
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>
And it worked for me .
Target container is not a DOM element.
I achieved this error with a simple starter app also.
// index.js
ReactDOM.render(
<Router>
<App />,
document.getElementById('root')
</Router>
);
Solution:
Syntax errors can cause this error. I checked my syntax and wrapped my <App /> properly.
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
In my case, I forget to add this line to the index.js file
document.getElementById('root')
and I forget to import react-dom import ReactDOM from 'react-dom'; so you can use ReactDOM later in the same file
Hope this will be helpful for you

When I have to use #section scripts?

My current structure has a layout with header, body and footer. Inside the body load a view using ajax to call for a action controller returning a Json and painting a tree view. When user click on the tree view the footer should load the detailed information. But isnt working, my guess is because the scripts section isnt render properly.
Right now the script are in the layout without bundles or anything and work ok on the Main body because I use Jquery and a Tree to load the Json data.
But in the partial View get an error. I could write a #section scripts area and copy all the script from the layout in the Partial View but why should I duplicate the code?
The worst part is only give me problem in the production enviroment ... on my devolpment enviroment works ok.
So the questions:
Why the main view can see the scripts define on the Layout but the Partial View Doesnt?
Why my development enviroment work ok, but productions doesnt?
What should I do to solve this?
EDIT: More testing.
This is a test View, this render in the Body. But I need include script section otherwise the dialog doesnt show, even when layout have the scripts too.
#{
ViewBag.Title = "TreeDetails";
}
<html>
<head>
<title>#ViewBag.Title</title>
</head>
<body>
<h2>TEST PAGE</h2>
<script>
// Your code goes here.
$(document).ready(function () {
console.log("before dialog");
$("#dialog").dialog();
console.log("after dialog");
})
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
</html>
#section scripts {
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
}
It seems a run time error due to an unrecognized jquery function.. try to move your link reference to jquery from your view #section area in the layout header..

How to create Backbone View in a separate js file

I'm trying to understand how to modularize the Backbone ToDo tutorial
Originally everything is inside the same file, but if I try to extract to another file:
var TodoView = Backbone.View.extend({
...
});
then this throws an error:
var view = new TodoView({model: todo});
**Uncaught TypeError: undefined is not a function**
It's probably due to a scope issue, but I don't know how to create a reference inside the $(function() so I can create this new object inside the main function.
Assuming that your first code part is TodoView.js,
and your second code part is app.js.
Write your html file like this,
<html>
<head>
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
// your dom
</body>
</html>
(Edited, at 2015-07-27)
sorry for my late reply.
how about this?
<html>
<head></head>
<body>
<!-- your dom -->
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
In many case, most javascript codes are appended to just before </body>, so that javascript can use your dom!
You can use something like require.js to load your external files and manage dependancies.
Ok, the solution was to move the script references to the end of the body instead of inside the head tags.
I think that the reason is that TodoView.js is making use of templates that were defined in the body, and since the js file was being loaded before the body, the templates were not yet available.

how to integrate TinyMCE and CKEditor in Meteor JS?

I am trying to use CKEditor or TinyMCE editor in my project.
So I put TinyMCE folder in meteor public folder, also put
<head>
<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
in template head tag.
However receiving following error.
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:3000/%3Cyour%20installation%20path%3E/tinymce/tinymce.min.js". (index):97
Uncaught SyntaxError: Unexpected token < tinymce.min.js:1
Uncaught ReferenceError: tinymce is not defined
How do I fix this problem? It is same to CKEditor.
Is there any other rich editor ,which I can use in Meteor JS?
First, you need to put everything from the CKEDITOR build download in the public folder. CKEDITOR comes with all sorts of stuff and references everything based on relative directories.
Your public folder should have a directory named ckeditor it should contain contain the following files and folders:
adapters
lang
plugins
skins
ckeditor.js
config.js
contents.css
styles.js
In your primary layout file reference CKEDITOR like so:
<head>
<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/ckeditor/adapters/jquery.js"></script>
</head>
In your template:
<template name="yourTemplate">
<textarea id="content" name="content"></textarea>
</template>
Finally, in the rendered function of your template:
Template.yourTemplate.rendered = function() {
$('#content').ckeditor();
};
Normally, you would say this.$('#content').ckeditor() but that doesn't work because CKEDITOR is in your public folder. As a result, you need to the global reference to the #content element.
Instead of /public folder, put your files in /client/compatibility. Then initialize it in the template you want to use it.
Template.editor.rendered = function() {
tinymce.init({
selector: 'textarea'
});
};
This was the only result searching for wysiwyg:
https://github.com/mcrider/meteor-bootstrap-wysiwyg
meteor add mcrider:bootstrap-wysiwyg
Looks a bit simpler than CKEditor or TinyMCE but maybe that's ok for your project.

Meteor.js: <script> tag doesn't work inside <body>

A simple script tag inside the body tag doesn't seem to work. The alert doesn't get triggered in the code below:
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{>main}}
</body>
Any idea why?
Edit:
Just tried it with a fresh meteor app, no alert tag still:
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
Weird thing is when I copy paste the source of the html, made a new html page, and the alert will work.
Edit3: I deployed this app here: http://alert-in-body-test.meteor.com/
Do you get an alert box?
This question is still relevant in the current version of Meteor (version 0.5.4) so I wanted to describe how to include script at the end of the body.
To execute javascript at the end of the body, register a Handlebars helper and put the relevant code there, like this:
In client.html:
<body>
{{renderPage}}
{{afterBody}}
</body>
...
In client.js:
if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('afterBody', function(name, options) {
$('body').append('AFTER BODY');
});
}
(For a great description of why this is required, see Rahul's answer to a similar question here: https://stackoverflow.com/a/14002991/219238 )
Its working for me
in onrender call this jquery
$.getScript('yours url')
It should work.
I have just pasted this inside one of my projects and it worked.
Your {{>main}} is strange for me tough. Also make sure that <body> is inside <html> tag.
Meteor is constructing the entire DOM from Javascript by rendering your page as a template -- the 'source' for your page as seen by the browser is basically:
<script type="text/javascript" src="/5a8a37bef5095c69bcd3844caf3532e1ba6d49bf.js"></script>
I can't find a definitive page stating that embedding a script tag in a template like this won't cause it to be executed, but it definitely feels against the spirit of what the framework is trying to achieve.
If the point is to achieve a clean separation of your markup and logic then why put it in the template. A better solution would be to use the meteor.startup call
Instead of looking the rendered html at developer tools, try looking the real downloaded html.
You will find a (probably) empty tag, with tons of script tags inside the .
In other words, the body of your meteor application is not the body of the final html, it's just your main template.
Instead, this ton on scripts shipped by Meteor, will load your templates.
So, your code will not run, cause it's been placed there. It's like when you manipulate DOM (with jQuery, for exemple), placing a script tag in DOM, after it's loaded. This script tag will not run.

Categories

Resources