How to reference a React class from generic javascript - javascript

I have this index.html :
<html>
<head>
<title>Sample App</title>
<link href="./src/css/bootstrap.min.css" rel="stylesheet" />
<link href="./src/css/bootstrap.dashboard.css" rel="stylesheet">
</head>
<body>
<div id='root'>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="./src/js/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:26665/signalr/hubs"></script>
<script type="text/javascript" src="/static/bundle.js"></script>
<script type="text/javascript">
$(function() {
var myHub = $.connection.signalRTwitchBotParserHub;
myHub.client.OnNewMessage = function (data) {
// Call AppActions.dispatchMessage(message);
};
$.connection.hub.url = "http://localhost:26665/signalr";
$.connection.hub.start()
});
</script>
</body>
How can I call a React-created class from there? I would like to replace the // Call AppActions.dispatchMessage(message);

You could do something like the following. What that does is create an instance of YourReactClass that renders itself as a child of your div with the id of root. It also passes the message as a property into the react instance so that it can make use of that data. Note that I added key="rootclass" to ensure that every time this code is called, React continues to reuse the DOM nodes created by the react class instead of removing the old nodes and adding new ones.
React.render((<YourReactClass key="rootclass" message={message} />), document.getElementById('root'));

You can include React onto the page by adding
<script src="https://fb.me/react-0.13.3.min.js"></script>
See the full list of downloads for other includable options (such as the JSX Transformer).

Related

Assigning a link and description to a column cards dynamically

I want to create column cards (like buttons).
in that cards, description should appear in its top and when it is clicked, separate link should be opened in new page.
every cards has its own description and link.it should not be hard coded by directly assigning the desc and link to it.and every function and elements should be assigned in javascript file not html.
the desc and link should given in an array like
Table={{"desc":"apple","link":"www.google.com"},{"desc":"banana","link":"www.youtube.com"}}
I tried this code and I'm getting only one card with last description and link
for(i=0;i<10;i++)
{
var temp=my.Table[i].link;
$('.demo').html('<div class="column"><p id="i"></p></div>');
document.getElementById(i).innerHTML ='' + my.Table[i].desc + '';
}
You can iterate the table object, after append what you should use.
HTML code:
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<div class="demo">
</div>
</body>
</html>
And the jquery code looks like the following:
$(document).ready(function(){
const table=[{"desc":"apple","link":"www.google.com"},{"desc":"banana","link":"www.youtube.com"}];
table.forEach((v, i)=>{
$('.demo').append('<div class="column"><p id="temp_'+i+'">' + v.desc + '</p></div>');
});
});

Running JavaScript libraries (Looper) in Blazor Server-side - some javascript code is not running

I am trying to implement Looper theme to my blazor server-side app, and I have the javascript libraries referenced at the end of the in _Host.cshtml.However some scripts in theme.min.js is not running. Why?
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script src="_framework/blazor.server.js"></script>
My problem is that while
<div data-toggle="drowndown"></div> works, but hamburger menu toggle
<button class="hamburger hamburger-squeeze mr-2" type="button" data-toggle="aside-menu" aria-label="toggle aside menu"><span class="hamburger-box"><span class="hamburger-inner"></span></span></button>
does not work. What am I missing here? What am I doing wrong? My theme change script also isn't running. If I step through theme.js and I can see that this script runs when blazor is not active (commenting out blazor.js) but with blazor active, this script does not run.
(line 610) in /library/javascript/theme.js
}, {
key: "toggleAside",
value: function toggleAside() {
var _this4 = this;
var $trigger = $('[data-toggle="aside"]');
$trigger.on('click', function () {
var isShown = $('.app-aside').hasClass('show');
$trigger.toggleClass('active', !isShown);
if (isShown) _this4.hideAside();else _this4.showAside();
});
}
My educated guess is that theme.js is using something that blazor does not allow? Is anybody experienced enough with Looper theme (or with javascript in general) to know why it wouldn't work? Particularly the hamburger toggle and the theme switching code
(line 1992 in /library/javascript/theme.js)
var Looper = function () {
var Looper = new Theme(); // toggle skin thought button
$('[data-toggle="skin"]').on('click', function (e) {
e.preventDefault();
var skin = Looper.skin === 'dark' ? 'default' : 'dark';
Looper.setSkin(skin); // we need to refresh our page after change the skin
location.reload();
}).each(function () {
var isDarkSkin = Looper.skin === 'dark';
var $icon = $(this).find('.fa-moon');
if (isDarkSkin) {
$icon.addClass('far');
$icon.removeClass('fas');
}
}); // make it global
return Looper;
}();
This is the website https://worshipground.azurewebsites.net/ You can use the inspector tool to see that blazor has been correctly loaded and all the javascript files are loaded in /library/javascript and /library/vendor/...
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- End Required meta tags -->
<title> Starter Template | Looper - Bootstrap 4 Admin Theme </title>
<base href="~/" />
<meta name="theme-color" content="#3063A0">
<link rel="apple-touch-icon" sizes="144x144" href="Library/apple-touch-icon.png">
<link rel="shortcut icon" href="Library/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:400,500,600" rel="stylesheet">
<link rel="stylesheet" href="/Library/vendor/open-iconic/font/css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="/Library/vendor/fontawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="/Library/stylesheets/theme.min.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/theme-dark.min.css" data-skin="dark">
<link rel="stylesheet" href="/Library/stylesheets/custom-app.css">
<link rel="stylesheet" href="/Library/stylesheets/custom.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/custom-dark.css" data-skin="dark">
<script>
var skin = localStorage.getItem('skin') || 'default';
var isCompact = JSON.parse(localStorage.getItem('hasCompactMenu'));
var disabledSkinStylesheet = document.querySelector('link[data-skin]:not([data-skin="' + skin + '"])');
// Disable unused skin immediately
disabledSkinStylesheet.setAttribute('rel', '');
disabledSkinStylesheet.setAttribute('disabled', true);
// add flag class to html immediately
if (isCompact == true) document.querySelector('html').classList.add('preparing-compact-menu');
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
You may find you have your work cut out in terms of making a JavaScript heavy template work nicely in Blazor.
You will probably need to utilise IJSRuntime
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0
I think I know where this problem comes from! If you comment out the following code on the "Host.cshtml" file, this problem will most likely go away!
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
But!!!! You will get some javascript errors related to "WebSocket" instead! something like this:
"WebSocket is not in the OPEN state"
Or
"Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State."
The cause of these errors is a conflict between "pace.min.js" file and "blazor.server.js" file! You can check this link for more information and get more help

Why emitted events of livewire is not triggered?

In laravel 7 learning livewire/livewire 1.3 I encountered that emitted
events are not always triggered
I created component with command
php artisan make:livewire hostel/hostelsHomepageSpotlight
and simplifying the code I do not see alert of event.
In app/Http/Livewire/Hostel/HostelsHomepageSpotlight.php :
<?php
namespace App\Http\Livewire\Hostel;
use Auth;
use DB;
use App\Config;
use App\Hostel;
use App\HostelImage;
use App\library\CheckValueType;
use App\Settings;
use Livewire\Component;
class HostelsHomepageSpotlight extends Component
{
public function render()
{
$hostels = [];
$current_page= 1;
$hostel_rows_count = Hostel
::getByStatus('A')
->count();
$this->emit('hostelsHomepageSpotlightOpened', [ 'mode'=> 'hostels_homepage_spotlight', 'current_page'=>$current_page, 'hostel_rows_count'=>$hostel_rows_count ] ); // EMIT EVENT
return view('livewire.hostel.hostels-homepage-spotlight', [
'hostelsDataRows' => $hostels,
'hostel_rows_count'=> $hostel_rows_count,
'current_page'=> $current_page,
]);
}
}
and in resources/views/livewire/hostel/hostels-homepage-spotlight.blade.php:
<div>
<h1>hostelsHomepageSpotlightOpened</h1>
</div>
<script>
// If to uncomment line below I see alert
// alert( 'resources/views/livewire/hostel/hostels-homepage-spotlight.blade.php::' )
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
// I DO NOT SEE ALERT BELOW ANYWAY
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
// alertsInit(data.mode)
// lazyImagesInit("img.lazy_image")
})
</script>
Why event is not triggered ? Is there is a way to debug it ?
UPDATED # 2:
I know the rule about wrapping div(without any class or styles definitions).
Have I also to remove JS code ?
I tried to move all JS code in resources/js/app.js :
window.$ = window.jQuery = require('jquery');
require('./bootstrap');
var Turbolinks = require("turbolinks")
Turbolinks.start()
// If to uncomment the line below I see it
// alert( '::resources/js/app.js' )
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
// I do not see this alert
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
// alertsInit(data.mode)
// lazyImagesInit("img.lazy_image")
})
and in my resources/views/layouts/app.blade.php :
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" xmlns:livewire="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel:Livewire</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
<link rel="icon" type="image/png" href="/favicon.ico"/>
<link href="/css/app.css" rel="stylesheet">
<script src="{{ asset('js/lazyload.js') }}"></script>
<!-- Styles -->
#livewireStyles
#livewireScripts
<script src="{{ asset('/js/app.js') }}"></script>
<script src="{{ asset('/js/app/app_funcs.js') }}"></script>
</head>
<body class="text-center">
<div class="flexbox-parent page_container " id="page_content">
<header class="flexbox-item header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
...
</nav>
</header>
<main class="flexbox-item fill-area content flexbox-item-grow">
#yield('content')
</main>
<footer class="flexbox-item footer ml-3 mr-3">
...
<p class="m-2">copyright_text</p>
</footer>
</div>
</body>
</html>
And my code is nit triggered anywat!
I suppose that is valid structure of my app as app.js AFTER #livewireStyles
and #livewireScripts
UPDATED # 3:
I tried and that does not work. I have login form :
<article class="page_content_container">
...
<form class="form-login" wire:submit.prevent="submit">
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control editable_field"
placeholder="Your email address"
autocomplete=off
>
</form>
...
</article> <!-- page_content_container -->
{{--#push('scripts')--}}
<script>
$("#email").focus();
</script>
{{--#endpush--}}
When #push/#endpush are commented as on lines above it works ok and focus is set to email input.
But if to uncomment these 2 lines focus is not set.
I modified my resources/views/layouts/app.blade.php :
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel:Livewire</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
<link rel="icon" type="image/png" href="/favicon.ico"/>
<link href="/css/app.css" rel="stylesheet">
<!-- Styles -->
#livewireStyles
<script src="{{ asset('/js/app.js') }}"></script>
<script src="{{ asset('js/lazyload.js') }}"></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.x.x/dist/alpine.min.js" defer></script>
#livewireScripts
#stack('scripts')
<script src="{{ asset('/js/app/app_funcs.js') }}"></script>
app.js - is first as bootstrap and jquery are included there...
Thanks!
Livewire expects components wrapped by a div element.
Sample:
< div>
Your content...
</ div>
What I am saying is that I am not sure you can include javascript in your Livewire blade. Try by moving it out to your app.js file and see if it works because the rest looks good.
I remember having trouble just because the blade’s first line was a html comment, instead of 🙈
So, always, first line of your livewire blade must be < div>, and last line </ div>
Hope that helps!
If you want to write script under livewire blade try this way. in your master layout put under #livewireScripts
#stack('scripts')
Now you can push scripts in this stack from your livewire blade file like this:
#push('scripts')
<script>
// some js code
</script>
#endpush
UPDATED: It makes sense why in your case it does NOT work. You should NOT emit the event in the RENDER function IFF you want to listen for it in the same view that is about to be rendered. In simple words for your case, the emit happens before the view loads, thus, by the moment your view is ready, it will be a 'bit' late to listen to it, you lost it! :-)
Solution: put the JS (the window.livewire.on... ) one step outside so it will be already ready by the moment you emit the event in the render.
In simple words, place the JS code in the scripts section of the parent file, the file you include the following
#livewire('hostel.hostels-homepage-spotlight')
P.S. When you are dealing with livewire, to listen for an event or fire one,
do not forget to wrap it in the document ready, i.e.,
$( document ).ready(function() {
livewire.emit('event_foo', 'foooo');
});
Thus, your spotlight PARENT page should look something like this:
<script>
$( document ).ready(function() {
window.livewire.on('hostelsHomepageSpotlightOpened', data => {
alert( 'hostelsHomepageSpotlightOpened::' )
console.log('facility_opened data::')
console.log(data)
});
});
</script>
Cheers,

React: Code not rendering on the website [duplicate]

I am tring to do react using below code but I am not getting html
element in the browser. There is no error in the console.
<!DOCTYPE html>
<html>
<head>
<title>React without npm</title>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">
var reactTest = React.createClass({
render: function(){
return(
<h1>React Without NPM</h1>
);
}
});
ReactDOM.render(<reactTest />,document.getElementById('test'));
</script>
</body>
</html>
Can someone please help on this.
If a React Class name starts with a lowercase letter then no methods inside the class get called, i.e. nothing Renders, and you don't get any error message in the Browser console,
because small letters are treated as HTML elements, its a rule that all React components must start with a upper case letter, so always use Upper Case.
Instead of reactTest use this: ReactTest it will work.
As per DOC:
User-Defined Components Must Be Capitalized.
When an element type starts with a lowercase letter, it refers to a
built-in component like <div> or <span> and results in a string 'div'
or 'span' passed to React.createElement. Types that start with a
capital letter like <Foo /> compile to React.createElement(Foo) and
correspond to a component defined or imported in your JavaScript file.
We recommend naming components with a capital letter. If you do have a
component that starts with a lowercase letter, assign it to a
capitalized variable before using it in JSX.
Check the working code:
<!DOCTYPE html>
<html>
<head>
<title>React without npm</title>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">
var ReactTest = React.createClass({
render: function(){
return(
<h1>React Without NPM</h1>
);
}
});
ReactDOM.render(<ReactTest />,document.getElementById('test'));
</script>
</body>
</html>
The following works fine, try it :
var ReactTest = React.createClass({
render: function(){
return(
<h1>React Without NPM</h1>
);
}
});
ReactDOM.render(<ReactTest />,document.getElementById('test'));
<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>
<div id="test" ></div>
const Some = ()=> <div />
<Some />
will work,
but
const some = () => <div />
<some />
won't work

Jquery not works for javascript innerHtml

Please have a look on code written below. I am trying to have a multiple timer on one page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" href="jquery.countdown.css" media="all" type="text/css" />
<style type="text/css">
#defaultCountdown { width: 240px; height: 40px; }
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.countdown.js"></script>
<script language="javascript" type="text/javascript">
function LoadText()
{
document.getElementById('dd').innerHTML = '<div id=\"defaultCountdown\" class=\"countdown\" rel=\"87401\">hjhg</div><br/><div id=\"defaultCountdown\" class=\"countdown\" rel=\"60\">hjgj</div><br/><div id=\"defaultCountdown\" class=\"countdown\" rel=\"1800\">hjhg</div><br/>';
}
</script>
</head>
<body>
<div id="dd">
</div>
<script type="text/javascript">
// Initialization
$(document).ready(function()
{
var date = new Date();
$('div.#defaultCountdown').each(function()
{
$(this).countdown
({
until:parseInt($(this).attr("rel"),10),
format:"DHMS",
expiryText:"Expired"
})
})
});
</script>
</body>
</html>
My code works fine when I create Divs Hardcoded. But when I load it through Ajax (For understanding of code, for the time being I am creating Divs using Function LoadText()), I am not able to get it displayed. Please help me out.
For one, you have this:
div.#defaultCountdown
which should be:
div#defaultCountdown
I don't see you calling your LoadText function anywhere
ID's are required to be unique within a document, and your LoadText function does not respect that rule
Unrelated, but you don't need to escape those double quotes inside of your single quoted string in LoadText
You should be using a class or unique IDs for the #defaultCountdown div.
Also this would confuse the selector engine since you are telling it to look for a class with a # sign in it:
$('div.#defaultCountdown').each(function()
Try changing it to a class and use:
$('div.defaultCountdown').each(function()
Update: Ok, the reason why your code isn't working is because the LoadText() function is never called. If you update your script to look like this, it will work (demo):
$(document).ready(function() {
// This is needed to simulate the ajax call
LoadText();
// set up countdown timers
var date = new Date();
$('div.countdown').each(function() {
$(this).countdown({
until: parseInt($(this).attr("rel"), 10),
format: "DHMS",
expiryText: "Expired"
});
});
});
sounds like a timing issue. your jQuery code runs when the data is rendered to the page not after your ajax query completes. Make that a function rather than something to run on ready and call it after the ajax finishes.
Your $('div.#defaultCountdown').each(function() loop runs once when the document is ready - if you subsequently add new divs using Ajax then you need to make sure you re-run your $('div.#defaultCountdown').each(function() code again now that new divs have been added.
The jQuery live() function is good for this.
The working Code if I am not using Ajax Response Text or JavaScript innerHTML. Any solution in this direction will be appriciated. Please find below the modified code that is working. In this code I have created the divs hardcoded. Both the codes can be tested by copying this codes and saving it to html file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Count Down Timer</title>
<link rel="stylesheet" href="jquery.countdown.css" media="all" type="text/css" />
<style type="text/css">
#defaultCountdown { width: 240px; height: 40px; }
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.countdown.js"></script>
<script language="javascript" type="text/javascript">
**//function LoadText()
// {
// document.getElementById('divo').innerHTML='<div id="defaultCountdown" class="countdown" rel="87401">aaa</div><br/><div id="defaultCountdown" class="countdown" rel="60">bbb</div><br/><div id="defaultCountdown" class="countdown" rel="1800">ccc</div><br/>';
// }**
// Initialization
$(document).ready(function()
{
var date = new Date();
$('div.countdown').each(function()
{
$(this).countdown
({
until:parseInt($(this).attr("rel"),10),
format:"DHMS",
expiryText:"Expired"
})
})
});
</script>
</head>
<body>
<div id="divo">
<div id="defaultCountdown" class="countdown" rel="87401">aaa</div><br/><div id="defaultCountdown" class="countdown" rel="60">bbb</div><br/><div id="defaultCountdown" class="countdown" rel="1800">ccc</div><br/>
</div>
</body>
</html>

Categories

Resources