How to use WebView to show React jsx file - reactjs

I can't see any support to React jsx local file. How can I use them in WebView ? Can someone help me .
I'm using in this case like this:
<WebView
source={{
uri: isAndroid
? 'file:///android_asset/android_asset/index.jsx'
: 'index.jsx'
}}
allowUniversalAccessFromFileURLs={true}
onShouldStartLoadWithRequest={request => {
return true
}}
useWebKit={false}
/>
UPDATE
I tried for hours but I can't find the way how to import React file to Javascript.
this is my react file like:
index.jsx
import * as React from 'react';`
export class TVChartContainer extends React.PureComponent {
componentDidMount(){ // Do something}
render(){
return (
<div
id={this.props.containerId}
className={'TVChartContainer'}
/>
);
}
}

You need to get HTML string. In WEB React you can render JSX by ReactDom but in ReactNative you can't do it.
The easiest way is generating html string according to your jsx and data. You can put everthing there. I show you several examples.
class MyInlineWeb extends Component {
componentDidMount(){ // Do something}
renderHtmlAndroid = (data) => {
return `<div>
<style>
.block {}
</style>
<div class="block">${data}<div>
<div>`
}
renderHtmliOs = (data) => {
return `<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">${data}</div>
</body>
</html>`
}
render() {
return (
<WebView
originWhitelist={['*']}
source={{html: isAndroid ? this.renderHtmlAndroid([]) : this.renderHtmliOs([])}}
/>
);
}
}

Related

Script with jsx and script without jsx not working on the same page

I have a page where I want to test some react code. Both scripts are working independently, if they are alone in the page. If I add both, the script with jsx does not work. Is there an explanation for that behavior? Is it not allowed?
There is nothing about the code. I am guessing the imports cannot live together.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title>My Website</title>
</head>
<body>
<div id="myroot"></div>
<div id="myBabel"></div>
<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/babel.min.js"></script>
<!-- Load our React component. -->
<script src="js/index2.js"></script>
<script type="text/babel" src="js/index.jsx"></script>
</body>
</html>
Here the index2.js contents:
class App extends React.Component {
render() {
return React.createElement("div", null, React.createElement("h1", null, " the list "));
}
}
ReactDOM.render(React.createElement(App,null,null),
document.getElementById("myroot"));
And here a React with jsx:
class App extends React.Component {
state = {
/* Initial State */
input: "",
reversedText: ""
};
/* handleChange() function to set a new state for input */
handleChange = event => {
const value = event.target.value;
this.setState({
input: value
});
};
/* handleReverse() function to reverse the input and set that as new state for reversedText*/
handleReverse = event => {
event.preventDefault();
const text = this.state.input;
this.setState({
reversedText: text
.split("")
.reverse()
.join("")
});
};
render() {
return (
<React.Fragment>
{ /* handleReverse() is called when the form is submitted */}
<form onSubmit={this.handleReverse}>
<div>
{ /* Render input entered */}
<label>Text: {this.state.input}</label>
</div>
<div>
{ /* handleChange() is triggered when text is entered */ }
<input
type="text"
value={this.state.input}
onChange={this.handleChange}
placeholder="Enter a text"
/>
</div>
<div>
<button>Reverse Text</button>
</div>
</form>
{ /* Render reversed text */}
<p>Reversed Text: {this.state.reversedText}</p>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("myBabel"));
Like I said, the imports are working alone but both at the same time in the HTML page are not.
class List extends React.Component {
render() {
return React.createElement("div", null, React.createElement("h1", null, " the list "));
}
}
ReactDOM.render(React.createElement(List,null,null),
document.getElementById("myroot"));
If you check the console logs for your code you will find this error -
Uncaught SyntaxError: Identifier 'App' has already been declared.
You have both your components identified as App. So React needs different identifiers to keep track of each component. I changed one of the class name from App to List. This will work. Make sure to name your components.

How to pass a json array in react?

First of all I want to clear this I am using cdn for react and using ajax for fetching the details from the json file.
So,I have a json file reactjs.json which looks like...
[
{
"e64fl7exv74vi4e99244cec26f4de1f":[ "image_1.jpg","image_2.jpg"]
}
]
index.html
<!DOCTYPE html>
<html>
<head>
<title>Image Viewer-Static</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/babel">
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
images: []
};
}
componentDidMount() {
axios.get('reactjs.json').then(res => {
console.log(res.data);
this.setState({ images: res.data });
});
}
render() {
const { images } = this.state;
return (
<div>
{this.state.images.map((images, index) => (
<PicturesList key={index} apikeys={images.e64fl7exv74vi4e99244cec26f4de1f} />
))}
</div>
);
}
}
class PicturesList extends React.Component {
render() {
return (
<img src={this.props.apikeys} alt={this.props.apikeys}/>
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById("root")
);
</script>
</body>
</html>
I want to show the image named image_1.jpg,image_2.jpg but this.props.apikeys fetch the value like image_1.jpg,image_2.jpg
images
But I want that it gives two values and show the two image.
I tried a lot to solve this but fails.Any suggestion and help will be welcomed.
Here you are setting the array [ "image_1.jpg","image_2.jpg"] to apiKeys in
<PicturesList key={index} apikeys={images.e64fl7exv74vi4e99244cec26f4de1f} />
So when you try to set the image src here
<img src={this.props.apikeys} alt={this.props.apikeys}/>
what you are setting as this.props.apikeys to src is an array. You have to handle the two images in the array separately to set the source of each image as a String. Try as follows.
{this.props.apikeys.map((image, index) => (
<img src={image} alt={image}/>
))}
since you already have the json file in the file structure you can just import and use it..
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import reactjsJSON from "./reactjs.json";
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
images: reactjsJSON
};
}
** Edit: **
Your html file
<!DOCTYPE html>
<html>
<head>
<title>Image Viewer-Static</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/babel">
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
images: []
};
}
componentDidMount() {
axios.get('/reactjs.json').then(res => {
console.log(res.data);
this.setState({ images: res.data });
});
}
render() {
const { images } = this.state;
return (
<div>
{ this.state.images.map(imageObjs =>
Object.keys(imageObjs).map(key =>
imageObjs[key].map((image, index) => (
<PicturesList key={index} apikeys={image} />
))
)
)}
</div>
);
}
}
class PicturesList extends React.Component {
render() {
console.log(this.props)
return (
<img src={this.props.apikeys} alt={this.props.apikeys}/>
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById("root")
);
</script>
</body>
</html>
Your JSON, tested for all possibilities, replaced with dummy images
[
{
"e64fl7exv74vi4e99244cec26f4de1f": [
"https://picsum.photos/200?image=2",
"https://picsum.photos/200?image=2"
],
"e64fl7exv74vi4e99244cec26f4deop": [
"https://picsum.photos/200?image=2",
"https://picsum.photos/200?image=2"
]
},
{
"e64fl7exv74vi4e99244cec26f4de1g": [
"https://picsum.photos/200?image=2",
"https://picsum.photos/200?image=2"
]
}
]
serve both the files in same http server and check the output.... since both files are served from same server u can add './' path to fetch and get JSON data...
Looks to me like you are receiving this JSON repose & then setting a JSON object into your state. Try looking at
JSON.parse()
. Your also setting the whole JSON object to your images array. You need select a key.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I write a demo in codesandbox: https://codesandbox.io/s/oorn5o162q, you can check it out.
I use two real image urls in json, and refine your component code.

How to use React.Component with renderToString method?

I tried to do the server side render using renderToString method.
function handleRender(req, res) {
const html = renderToString(
<Counter />
);
res.send(renderFullPage(html));
}
function renderFullPage(html) {
return `
<!doctype html>
<html>
<head>
<title>React Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
If the component like following it works:
Counter.js
const Counter = () => {
function testClick(){
console.log('test');
}
return (
<div>
<div onClick={testClick.bind(this)}>
test
</div>
</div>
);
};
export default Counter;
However, if I change Counter.js into following:
class Counter extends React.Component {
testClick(){
console.log('click');
}
render() {
return (
<div>
<div onClick={this.testClick.bind(this)}>
test btn
</div>
</div>
)
}
}
export default Counter;
It will show errors:
Uncaught Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration.
So how to use React.Component with renderToString method?
I minimize the project and push to Github. Please have a look.
https://github.com/ovojhking/ssrTest/tree/master

Load Google Place API in Gatsbyjs (Reactjs) project

I am trying to use the AutoComplete address service from Google Place API.
Found this library:
https://github.com/kenny-hibino/react-places-autocomplete#load-google-library
It asks for loading the library in my project:
https://github.com/kenny-hibino/react-places-autocomplete#getting-started
I would do it in the public/index.html if it's pure Reactjs project. However, the public/index.html in Gatsbyjs project will be deleted and re-generated every time when running:
Gatsby develop
command line.
How can I use the Google Place API in my Gatsbyjs project?
Update
I have tried 2 ways to achieve this.
Use React-Helmet in /layouts/index.js , here is how it looks like:
<Helmet>
<script src="https://maps.googleapis.com/maps/api/js?key={API}&libraries=places&callback=initAutocomplete" async defer></script>
</Helmet>
Put the script reference in the /public/index.html, which looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charSet="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title data-react-helmet="true"></title>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={API_KEY}&libraries=places" async defer ></script>
</head>
<body>
<div id="___gatsby"></div>
<script src="/commons.js"></script>
</body>
</html>
For the 1st solution, every time after I refresh my page, the project throws an error asking for loading the Google JavaScript Map API.
For the 2nd solution, every time after I re-start the Gatsby by the command line: gatsby develop
it re-generates the index.html which flushes away my JavaScript reference in it.
You shouldn't modify any files in the public forlder with GatsbyJS.
Instead, I recommend you to customize your html.js file.
To do so, first run:
cp .cache/default-html.js src/html.js
You should have the html.js file in /src/html.js.
Now you can put your <script> tag within the <head>.
Update Feb 24, 2020
Here's a more modern implementation using React hooks with some performance optimizations based on React.memo and a custom shouldUpdate function. See this blog post for details.
import { functions, isEqual, omit } from 'lodash'
import React, { useState, useEffect, useRef } from 'react'
function Map({ options, onMount, className, onMountProps }) {
const ref = useRef()
const [map, setMap] = useState()
useEffect(() => {
// The Map constructor modifies its options object in place by adding
// a mapTypeId with default value 'roadmap'. This confuses shouldNotUpdate.
// { ...options } prevents this by passing in a copy.
const onLoad = () =>
setMap(new window.google.maps.Map(ref.current, { ...options }))
if (!window.google) {
const script = document.createElement(`script`)
script.src = `https://maps.googleapis.com/maps/api/js?key=` + YOUR_API_KEY
document.head.append(script)
script.addEventListener(`load`, onLoad)
return () => script.removeEventListener(`load`, onLoad)
} else onLoad()
}, [options])
if (map && typeof onMount === `function`) onMount(map, onMountProps)
return (
<div
style={{ height: `60vh`, margin: ` 1em 0`, borderRadius: ` 0.5em` }}
{...{ ref, className }}
/>
)
}
function shouldNotUpdate(props, nextProps) {
const [funcs, nextFuncs] = [functions(props), functions(nextProps)]
const noPropChange = isEqual(omit(props, funcs), omit(nextProps, nextFuncs))
const noFuncChange =
funcs.length === nextFuncs.length &&
funcs.every(fn => props[fn].toString() === nextProps[fn].toString())
return noPropChange && noFuncChange
}
export default React.memo(Map, shouldNotUpdate)
Map.defaultProps = {
options: {
center: { lat: 48, lng: 8 },
zoom: 5,
},
}
Old Answer
Using html.js
Modifying src/html.js like so (as Nenu suggests) is one option.
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class HTML extends Component {
render() {
return (
<html {...this.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"
/>
{this.props.headComponents}
</head>
<body {...this.props.bodyAttributes}>
{this.props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
// MODIFICATION // ===================
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
async
defer
/>
// ===================
</body>
</html>
)
}
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
Then you can access the Google Maps API anywhere in your project from window.google.maps.(Map|Marker|etc.).
The React way
To me that felt a little anachronistic, though. If you want a reusable React component that you can import into any page or template as import Map from './Map', I suggest this instead. (Hint: See update below for equivalent function component.)
// src/components/Map.js
import React, { Component } from 'react'
export default class Map extends Component {
onLoad = () => {
const map = new window.google.maps.Map(
document.getElementById(this.props.id),
this.props.options
)
this.props.onMount(map)
}
componentDidMount() {
if (!window.google) {
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = `https://maps.google.com/maps/api/js?key=YOUR_API_KEY`
const headScript = document.getElementsByTagName('script')[0]
headScript.parentNode.insertBefore(script, headScript)
script.addEventListener('load', () => {
this.onLoad()
})
} else {
this.onLoad()
}
}
render() {
return <div style={{ height: `50vh` }} id={this.props.id} />
}
}
Use it like so:
// src/pages/contact.js
import React from 'react'
import Map from '../components/Map'
const center = { lat: 50, lng: 10 }
const mapProps = {
options: {
center,
zoom: 8,
},
onMount: map => {
new window.google.maps.Marker({
position: center,
map,
title: 'Europe',
})
},
}
export default function Contact() {
return (
<>
<h1>Contact</h1>
<Map id="contactMap" {...mapProps} />
</>
)
}
What woked for me was to create a gatsby-ssr.js file in the root of my project, and then include the script there, like this:
import React from "react"
export function onRenderBody({ setHeadComponents }) {
setHeadComponents([
<script
key="abc"
type="text/javascript"
src={`https://maps.googleapis.com/maps/api/js?key=${process.env.GATSBY_API_KEY}&libraries=places`}
/>,
])
}
Don't forget to include GATSBY_API_KEY or whatever you want to call it in your .env.development and .env.production files:
GATSBY_API_KEY=...

integrating js code inside react component

I have converted a component that displays chart bar, and it requires this js snippet to run, what is the correct way of integrating it inside my JSX code?
<script>
/** START JS Init "Peity" Bar (Sidebars/With Avatar & Stats) from sidebar-avatar-stats.html **/
$(".bar.peity-bar-primary-avatar-stats").peity("bar", {
fill: ["#2D99DC"],
width: 130,
})
</script>
I have seen this libraries on npm website, but they mostly deal with external scripts not internal
here is my component:
import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div>
"How can I render js code here?"
</div>
);
}
}
You can use refs and componentDidMount callback in order to initialize jquery plugins, like so
class App extends React.Component {
componentDidMount() {
$(this.barChart).peity("bar", {
fill: ["#2D99DC"], width: 130
});
}
render() {
return <div>
<div ref={ (node) => { this.barChart = node } }>
<span class="bar">5,3,9,6,5,9,7,3,5,2</span>
<span class="bar">5,3,2,-1,-3,-2,2,3,5,2</span>
<span class="bar">0,-3,-6,-4,-5,-4,-7,-3,-5,-2</span>
</div>
</div>;
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/peity/3.2.1/jquery.peity.js"></script>
<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="container"></div>
You should use componentDidMount lifecycle hook.
Add this to your component code:
componentDidMount() {
$(".bar.peity-bar-primary-avatar-stats").peity("bar", {
fill: ["#2D99DC"],
width: 130,
})
}

Resources