how to call react component code from renderer.js? - javascript

Hi I am new to React/JS and Electron and would like to write a desktop application using these technologies.
The problem I am facing now is that I am not sure how to call react component code from renderer.js. I have such coding structure.
electron-tutorial
src/
components/Test.js
application.js
electron-starter.js
mainWindow.html
package.json
And this is a list of code snippet of each file.
package.json:
"main": "src/electron-starter.js",
electron-starter.js
const application = require("./application");
global.application = new application();
global.application.run();
application.js
odule.exports = class Application {
createWindow() {
this.mainWindow = new BrowserWindow({
width: 1366,
height: 768,
...
pathname: path.join(__dirname, "./mainWindow.html"),
mainWindow.html
<body>
<div id="test"></div>
<script src="./renderer.js"></script>
</body>
So from mainWindow.html I want to call renderer.js. I learned that I know I can call functions in such way:
renderer.js
"use strict";
const { shell } = require("electron");
function hoge() {
console.log("hoge");
}
window.hoge();
But what I want to do is to call the react component below from renderer.js.
Test.js
import React from "react";
export class Test extends React.Component {
render() {
return <h1>Hello from Test class</h1>;
}
}
Could you please help me ? Thanks for reading !

As you are just starting out, I would recommend that you use a boilerplate like Electron-React.

Related

How can I embed VaniilaJS into React?

I have open source library that I want to use. the library wrote in clean vanilla js:
follow their docs, if I want to use the library:
<html>
<head>
<script src="./jquery-2.0.3.min.js"></script>
<script src="./kinetic-v5.1.0.min.js"></script>
<script src="./inchlib-1.2.0.js"></script>
<script>
$(document).ready(function() { //run when the whole page is loaded
var inchlib = new InCHlib({"target": "inchlib",
"width": 800,
"height": 1200,
"column_metadata_colors": "RdLrBu",
"heatmap_colors": "RdBkGr",
"max_percentile": 90,
"middle_percentile": 60,
"min_percentile": 10,
"heatmap_font_color": "white",
text: 'biojs'});
inchlib.read_data_from_file("/microarrays.json");
inchlib.draw();
inchlib.onAll(function(name){
console.log(name + " event triggered");
});
});
</script>
</head>
<body>
<div class="heatmaps" style="margin:auto; align-items: center; margin-left:25%;">
<div id="inchlib"></div>
</div>
<div ></div>
</body>
</html>
The file inchlib-1.2.0.js contains the main logic and js code. I want to build react project and use this library there. How can I achieve this goal?
import React, { Component } from 'react';
import './App.css';
export default class App extends Component {
render () {
return (
<div>
<div>
</div>
</div>
)
}
}
You can create custom hook with useEffect. In useEffect you should paste your code. You can insert html elements, add event listeners and so on.
useLibrary.js
import { useEffect } from "react";
const useLibrary = () => {
useEffect(() => {
$.getScript("inchlib-1.2.0.js", function(){
var inchlib = new InCHlib({"target": "inchlib",
"width": 800,
"height": 1200,
"column_metadata_colors": "RdLrBu",
"heatmap_colors": "RdBkGr",
"max_percentile": 90,
"middle_percentile": 60,
"min_percentile": 10,
"heatmap_font_color": "white",
text: 'biojs'});
inchlib.read_data_from_file("/microarrays.json");
inchlib.draw();
inchlib.onAll(function(name){
console.log(name + " event triggered");
});
});
}, []);
};
export default useLibrary;
App.js
import useLibrary from ".useLibrary";
export default class App extends Component {
useLibrary();
render () {
return (
<div>
<div class="heatmaps" style="margin:auto; align-items: center; margin-left:25%;">
<div id="inchlib"></div>
</div>
</div>
)
}
}
But I warn you that this is a big crutch.
Depends on what you're gonna do with the library you want to integrate with. Checkout this as a base reference: Integrating with other libraries.
If you're gonna manipulate DOM elements you'll gonna need a reference to them. In this case checkout this: Refs and the DOM.
If the library provides some general logic, you have no problem using it anywhere throughout your code or more specifically in effects.
As inchlib is a visual element library, you'll need to go the first route and get a reference to a specific DOM element. As already noted, checkout Refs from react docs.
Alternative solution is to wrap the whole library usage in your own react component.
Well If I were to do the same thing then I would paste the script tags as you've done in your html file
<head>
<script src="./jquery-2.0.3.min.js"></script>
<script src="./kinetic-v5.1.0.min.js"></script>
<script src="./inchlib-1.2.0.js"></script>
<script>
</head>
For accessing an object into react app, Create a file named Inchlib.js in same directory as is your app.js
Contents of Inchlib.js should be
export default window.InCHlib;
Import the default export into your app.js
import InCHlib from "./inchlib";
function App() {
console.log(InCHlib); // prints the InCHlib object
return "hello";
}
Note: Although this should work, there might be a better way to do this. Also using global objects in react code is not usually a preferred option.
Hopefully this would help.
Just add the Libraries and Scripts you want in the public/index.html file in your react project.
create loadScript function:
function loadScript(src, position, id) {
if (!position) {
return;
}
const script = document.createElement('script');
script.setAttribute('async', '');
script.setAttribute('id', id);
script.src = src;
position.appendChild(script);
}
in Component:
export default function GoogleMaps() {
const loaded = React.useRef(false);
if (typeof window !== 'undefined' && !loaded.current) {
if (!document.querySelector('#google-maps')) {
loadScript(
'https://maps.googleapis.com/maps/api/js?key=AIzaSyBwRp1e12ec1vOTtGiA4fcCt2sCUS78UYc&libraries=places',
document.querySelector('head'),
'google-maps',
);
}
loaded.current = true;
}
}
now you can access window.google
here is a example

How to construct js object in React

I have some problems with React and Advertisement.
Wanna use 'Coupang' Advertisement, but they support the script library only.
I can add it to 'index.html' in the public directory, but cannot customize the location.
here is the code,
<script src="https://ads-partners.coupang.com/g.js"></script>
<script>
new PartnersCoupang.G({"id":23232,"subId":null});
</script>
It's a dynamic advertisement.
How can I add it to the React functional component??
MB this will be helpful.
useScript will help you add script to your code dynamically.
and you custom hook (just create PartnersCoupang);
const usePartnersCoupang = () => {
const const [loaded, error] = useScript('https://ads-partners.coupang.com/g.js');
React.useEffect(() => {
if (loaded) {
new PartnersCoupang.G({"id":23232,"subId":null});
}
}, [loaded]);
React.useEffect(() => {
if (error) {
console.error('PartnersCoupang Failed.');
}
}, [error]);
}
Actually, you should eject from your create-react-app project by this command:
$ yarn eject
or:
$ npm run eject
Then you can see a folder that name is config, in this folder you can see all configuration of your project, especially your Webpack configs, then you should add your external library to the webpack as external key on the configuration of Webpack:
// webpack.config.js
...
module.exports = {
...
externals: {
PartnersCoupang: '[path-to]/g.js',
},
...
};
Then in your component import it easily:
import React, { Component } from 'react';
import PartnersCoupang from 'PartnersCoupang';
class YourComponent extends Component {
componentDidMount() {
new PartnersCoupang.G({"id":23232,"subId":null});
}
}

jQuery plugin not accessible in React

I have not been successful in importing the following jQuery plugin into my React app:
http://bililite.com/inc/jquery.parsecss.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://bililite.com/inc/jquery.parsecss.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
My React component:
import React, { Component } from "react";
class Main extends Component {
constructor(props) {
super(props);
$.parsecss(".mybutton { color: #ff0000; }", function(css) {
var x = 0;
x++;
});
}
}
The jQuery function parsecss is undefined.
Adding it to my index.html using a script tag did not work. Only when adding it as a node module and importing it, did it work. Of course, many jquery plugins are not available using npm, so I had to create my own package. This was actually quite simple. In my node_modules folder I created a folder called parsecss and a sub folder called dist. In dist I placed the jquery plugin. In the parsecss folder I added a package.json file that had the following content:
{
"main": "dist/jquery.parsecss.js",
"name": "parsecss",
"title": "parsecss"
}
You need to add jQuery as I showed in my sample code above in the index.html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
And in the React component:
/* global $ */
import React, { Component } from "react";
import parsecss from 'parsecss'
class Main extends Component {
constructor() {
$.parsecss(".mybutton { color: #ff0000; }", function(css) {
var x = 0;
x++;
});
}
}
Note: The comment /* global $ */ fixes a console error that indicates that $ is not defined.

How to use external js files in reactjs

I am trying to convert bootstrap 4 template into reactjs bootstrap is working fine but there are other javascript plugins also and I don't know how to use .
Any suggestions would be appreciated.
Update: Please, don't mix jQuery and React. It could be difficult to handle the DOM and VirtualDOM. Just try it if you really need to:
Try to invoke the scripts and append it when componentDidMount at Root component. Here is a snippet:
//#Write some like this in the App.js for example, since it's the main component:
componentDidMount(){
//An array of assets
let scripts = [
{ src: "assets/vendor/jquery/jquery.js" },
{ src: "assets/vendor/bootstrap/js/bootstrap.js" },
{ src: "assets/vendor/jquery-placeholder/jquery.placeholder.js" },
{ src: "assets/javascripts/theme.js" },
{ src: "assets/javascripts/theme.custom.js" },
{ src: "assets/javascripts/theme.init.js" }
]
//Append the script element on each iteration
scripts.forEach(item => {
const script = document.createElement("script")
script.src = item.src
script.async = true
document.body.appendChild(script)
})
}
Include the script tag in your index.html
Let's say if you want to include JQuery in your ReactJs app
Include following in index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Use this in following code and it works well
import React, { Component } from 'react';
class App extends Component {
constructor(){
super()
this.callJquery = this.callJquery.bind(this);
}
callJquery(){
window.$("#sample").click(function(){
alert("Text: Button Clicked");
});
}
render() {
return (
<div className="App">
<div id="sample" onClick={this.callJquery}> Hellow </div>
</div>
);
}
}
export default App;
Similarly, you can use any library by including in index.html and then use it.

Making site multi language support using google translate for React js

For simple html projects i can simple refer this link.
https://www.w3schools.com/howto/howto_google_translate.asp
But I'm trying to implement in react app . So I'm not able to replicate the code in react app.
componentDidMount() {
googleTranslateElementInit(() => {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
});
const script = document.createElement("script");
script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
script.async = true;
document.body.appendChild(script);
}
And return render element .
render() {
return (
<div id="google_translate_element"></div>
);
}
This is showing me error saying google , googleTranslateElementInit is not defined.
How can I use google translator in react app ?
Also is there any npm packages which can translate whole site ?
Thanks
Move your google translate script to the root index.html of your project.
However, you should leave the below code at your desired location:
render() {
return (
<div id="google_translate_element"></div>
);
}
Fixes the problem easily.
Change render to:
render() {
return (
<script type='text/javascript' src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit' />
<div id="google_translate_element"></div>
);
}
Create googleTranslateElementInit and use window.google instead of google:
googleTranslateElementInit () {
/* eslint-disable no-new */
new window.google.translate.TranslateElement({pageLanguage: 'pt', layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element')
}
Change componentDidMount to:
componentDidMount () {
window.googleTranslateElementInit = this.googleTranslateElementInit
}
For those in 2021 and hopefully a few more years before Google decides to change implementation method, this is how I resolved it.
Add the below script to your index.html file found in the public directory:
<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" async></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{
pageLanguage: "en",
layout: window.google.translate.TranslateElement.InlineLayout.VERTICAL,
},
'google_translate_element'
);
}
</script>
Then, create a component, to be imported anywhere you want to use the translate plugin, with any name of your choice. I will use GoogleTranslate.jsx for this purpose of this answer.
In the newly created component, paste this code:
import React, { useEffect } from "react";
const GoogleTranslate = () => {
useEffect(() => {
// in some cases, the google translate script adds a style to the opening html tag.
// this added style disables scrolling.
// the next 3 lines removes this added style in order to re-enable scrolling.
if (window.document.scrollingElement.hasAttribute("style")) {
window.document.scrollingElement.setAttribute("style", "");
}
});
return (
<div id="google_translate_element"></div>
);
};
export default GoogleTranslate;
Import the component wherever you want to use the translate plugin.
If this solution worked for you, kindly up vote so it can easily be shown to others searching. If it didn't, don't hesitate to drop a comment
Go to public folder > index.html
add code in body tag
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
create component
import React from 'react';
import './style.css';
const GoogleTranslate = (props) => {
return(
<div id="google_translate_element"></div>
)
}
export default GoogleTranslate
import GoogleTranslate from './GoogleTranslate';
<GoogleTranslate />

Categories