How to use baseURL in react-native-webview? - reactjs

I can't get the baseUrl parameter to work in react-native-webview. My project structure is as follows:
root
---> _tests _
---> android
-------> web
---> ios
---> node_modules
---> src
-------> components
------------> web
------------> MyComponent.js
---> web
I have inserted the web folder 3 times as shown (actually only need to once, this is just for testing). Each 'web' folder contains ponies.jpg. However, nothing is picked up by React Native. I just get 4 broken images with the alt (i.e. 'Ponies') showing. I have also tried using baseUrl: 'web/' to no avail. Here is the code in MyComponent.js:
import React from 'react';
import {View, Text, StyleSheet, Image} from "react-native";
import {WebView} from "react-native-webview";
var html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="ponies.jpg" alt="Ponies" height="42" width="42">
<img src="ponies.jpeg" alt="Ponies" height="42" width="42">
<img src="./ponies.jpg" alt="Ponies" height="42" width="42">
<img src="./ponies.jpeg" alt="Ponies" height="42" width="42">
</body>
</html>
`;
export default class MyComponent extends React.Component {
render() {
return (
<View style = {styles.container}>
<WebView
style = {styles.webview}
source = {{html: html, baseUrl: 'web/'}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 350,
width: 350
},
webview: {
height: 350,
}
})
Thankyou!

OK so I found a solution/workaround for android :D Have actually seen this in another answer but am going to expand a little:
baseUrl needs to be 'file:///android_asset/'.
You then create a directory in the android folder i.e. 'root/android/app/src/main/assets' (see this answer for details how to reference an asset in a library project).
These two folders are now the same. anything you put in assets should be seen by the webview.
IMPORTANT - I then had to rerun 'react-native run-android' to get the image to show up.

Currently, your web folder is inside the android folder
Add a folder web and used this structure:
app/web/ponies.jpg
Use web/ as base URL.
The final piece of the puzzle is to add the web folder to the XCode project (do this in XCode). Otherwise, the files in the web folder are not included in the bundle built for the ios device.
Note: where app is the root of the application.

Related

To publish Unity default AR Project with React Unity WebGL has a different serialization error

Development Environment
Macbook M1 Pro (With Apple Silicon Chip)
Unity 2021.3.10f1 (Be compatible with Apple Silicon Chip)
Test with Chrome Browser
Current Progress
I just create a new project with AR template
The project's hierarchy is like below picture.
That building Setting is like below picture.
After building, I get 4 files named build.data, build.framework.js, build.loader.js, build.wasm
With a create-react-app command, I created a new react project. (npx create-react-app ar_tutorial_4 --template typescript)
I located those 4 build files under the react's build directory. Like below image.
I edited index.html file like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>React Unity webGL</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
And, I edited App.tsx file and index.tsx file like this.
// App.tsx
import { useRef } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function UnityTest() {
const {
unityProvider,
isLoaded,
loadingProgression,
} = useUnityContext({
codeUrl: '/build/build.wasm',
dataUrl: '/build/build.data',
frameworkUrl: '/build/build.framework.js',
loaderUrl: '/build/build.loader.js',
webglContextAttributes: {
preserveDrawingBuffer: true,
},
});
const loadingPercentage = Math.round(loadingProgression * 100);
const canvasRef = useRef<HTMLCanvasElement>(null);
return (
<div className="container">
{isLoaded === false && (
<div className="loading-overlay">
<p>Loading... ({loadingPercentage}%)</p>
</div>
)}
<Unity
className="unity"
unityProvider={unityProvider}
style={{ border: "1px solid red", height: 400, width: 500 }}
devicePixelRatio={window.devicePixelRatio}
ref={canvasRef}
/>
</div>
);
}
export { UnityTest };
// index.tsx
import React, { createElement } from 'react';
import ReactDOM from 'react-dom/client';
import { UnityTest } from './App';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(createElement(UnityTest));
Problem
The screen was normally disappeared but the unity container did not played well.
And, this console error message was displayed.
build.framework.js:1771 A scripted object (script unknown or not yet loaded) has a different serialization layout when loading. (Read 52 bytes but expected 76 bytes)
Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
Question
What should I do to resolve this problem??

React Component not working properly with Mapbox

I'm new on React, but due to requirements at an assigment in college, I must use it . I must do a single page application (SPA), with various components. I used npx create-react-app to setup the base project, and so you have an idea, it looks like this right now:
Each functionality such as "create new node", "create new line", etc, is an individual component.
On my App.js, I'm setting a state for each component as false, only making it true when the key of the submenu associated with that specific component is clicked, allowing me to switch between the sidebar options with no problem, and then at each component, I have display: false at the state and also this:
componentWillUpdate(nextprops) {
if (nextprops.display !== this.props.display) {
this.setState({ display: nextprops.display });
}
}
so it makes that display true, so that component is loaded. Everything works nicely, only the map viewer has a problem where the map by mapboxgl displays in full screen, covering the sidebar, not allowing me to change between components. The MapViewer component code is:
import React, { Component } from "react";
import mapboxgl from "mapbox-gl";
//import 'mapbox-gl/dist/mapbox-gl.css'
mapboxgl.accessToken="MY_KEY_IS_HERE";
class MapViewerComp extends Component {
constructor(props) {
super(props);
this.state = {
longitude: -8.562298,
latitude: 41.187181,
zoom: 12,
display: false,
};
}
componentWillUpdate(nextprops) {
if (nextprops.display !== this.props.display) {
this.setState({ display: nextprops.display });
}
}
displayTheMap = () => {
const map = new mapboxgl.Map({
container: "root",
style: "mapbox://styles/mapbox/streets-v11",
center: [this.state.longitude, this.state.latitude],
zoom: this.state.zoom
});
var marker = new mapboxgl.Marker().setLngLat([-8.562298, 41.187181]).addTo(map);
};
render() {
let pageContent = <div></div>;
if (this.state.display) {
pageContent = (
<div>
<div ref={this.displayTheMap} className="mapContainer"/>
</div>
);
}
return <div>{pageContent}</div>;
}
}
export default MapViewerComp;
And the .css looks like this:
.ant-switch-handle {
text-align: right;
}
.mapContainer {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
}
When I click the "Map Viewer" option on my sidebar (which corresponds to my (MapViewerComp), it pops out like this:
Since I'm new to React and frontend, the only was I was able to force it to fit my screen like this:
was to add this piece to the .css of this component:
.mapboxgl-canvas{
position: absolute;
left: 271px;
top: 65px;
}
The 2 problems are:
1st: if I force it to the size I want like I showed you, now when I zoom in and out on the map, the marker moves around and doesn't stay in place.
2nd: when I click the other options on the sidebar, to switch between functionalities, it doesn't work, it keeps showing the map.
The code of the index.js at src(with the npx create-react-app structure) is:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/app/App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
And the code for the index.html on public folder is:
<!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"/>
<script src="../src/components/mapViewerComp/MapViewerComp.js"></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v1.13.0/mapbox-gl.css' rel='stylesheet' />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
here's the structure of the project as well if it helps in any way:
Any fix to any of the issues would be appreciated. All other components work like a charm, yet the map viewer is not...
Thank you in advance.
Edit: Turns out the mapbox is set to render inside of the app root container, which why it is taking all the available space and not going away when re-rendering the app. Setting margins exposes the sidebar and allows to interact with it but alas doesn't trigger the map to go away.
See the doc here.

React component library, Fonts not working

I created a component library in react using styled component. The library contains some custom fonts, in different formats, woff, woff,eot, tff, otf and etc. when I use the fonts inside the component library, the fonts works as it should.
The problem arises, when I import the library in another react project. When I look at the node modules, I can se that the fonts are included. The project is bade using React and Next.js. am I missing some important steps to use these fonts?
I don´t get any error. The application, just use the fallback font specified. I I´m not interested in changing the font of my of my whole application. I want to be able to access the font exported with my component Library, and use them in some places og my application.
An example:
My component Library contains the component "Headline", which use a custom font.
export const h1CSS = cssStyled`
margin-top: ...;
margin-bottom: ...;
line-height: ...;
font-weight: ...;
color: ...;
font-family: "Some_custom_Font";
font-style: normal;
margin-top: 0;
text-rendering: optimizeLegibility;
`;
In the application, which import the component Library, I can use the Headline component. The only problem is that the headline component does not have the custom font, when used inside my application.
Without knowing the error messages or all others aspect that hard to tell what exactly you need to do.
But You can customised the Document _document.js for your need. Which is more efficient to solve.
To override the default Document, create the file ./pages/_document.js and extend the Document class as shown below:
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
//You can add custom Favicon from here also
<link rel="icon" href={Favicon_URL} type="image/png" />
<meta
httpEquiv="cache-control"
content="no-cache, nostore, must-revalidate"
/>
<meta httpEquiv="pragma" content="no-cache" />
<meta httpEquiv="expires" content="0" />
//Please add your woff, woff,eot, tff, otf files here.
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Official Documentation page

Including external JavaScript libraries in new react app which is configured using create-react-app

I am new to react.js. I downloaded a theme which have external JavaScript libraries i.e bootstrap.min.js , jquery.min.js, slider.js, jquery-flexslider.min.js.
I created a React app using create-react-app and I copied all the external JavaScript libraries and CSS files in index.html of the public folder of my react app and copied all the html of index.html of my theme in app.js which I downloaded. All the CSS are working fine but the JavaScript libraries are not working on the page.
Following is the demo of how I included the css files and javascript libraries in index.html of the public folder.
<script src="/assets/javascript/jquery.min.js"></script>
<script src="/assets/javascript/bootstrap.min.js"></script>
<script src="/assets/javascript/jquery.easing.js"></script>
<script src="/assets/javascript/jquery-waypoints.js"></script>
<link rel="stylesheet" type="text/css"href="/assets/stylesheets/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="/assets/stylesheets/style.css"/>
<link rel="stylesheet" type="text/css" href="/assets/stylesheets/responsive.css"/>`
Now my question is, how should I include the JavaScript libraries so that it start working. I tried to put all the files in the src folder of my react app but it still not working.
You should consider using react-bootstrap instead of jquery and a minified bootstrap file. By using react-bootstrap you get bootstrap 3 (4 is in the works) as nicely designed react components that you can selectively import and use. So then you can
import React from 'react'
import{ string } from 'prop-types'
import { Col, Row, Label } from 'react-bootstrap'
const PrettyThing = ({ thing }) => (
<Row>
<Col xs={9} xsOffset={1}>
<Label bsStyle="success">{thing}</Label>
</Col>
</Row>
)
PrettyThing.propTypes = { thing: string.isRequired }
export default PrettyThing
and webpack will handle how that's all sliced and diced so only the css you need gets built.
see https://react-bootstrap.github.io/getting-started/introduction/ for more info.

Using React-Native with a Web Application

I have installed Expo XDE, and created a new project funproject. I understand that the XDE is meant for devices and I could connect my virtual devices.
However, I would also like to reuse the same code base for a web application.
I have broused to the location on my localhost where the app should be.
http://localhost:19001/
This looks right, I can see the index.html page. It's actual file path is.
funproject\node_modules\react-native\local-cli\server\middleware\index.html
Here are the contents of the index.html
<!DOCTYPE html>
<html>
<head>
<title>React Native</title>
</head>
<body>
<p>React Native packager is running.</p>
<p>Visit documentation</p>
</body>
</html>
So I added a div for the content and the script, app.js
<!DOCTYPE html>
<html>
<head>
<title>React Native</title>
</head>
<div id="content"></div>
<body>
<p>React Native packager is running.</p>
<p>Visit documentation</p>
</body>
</html>
<script type="text/javascript" src="../app.js"></script>
I am new to react, but the idea that I can target web, and mobile all in one, is very enticing. Unfortunately this does not work! When I use chrome developer tools, I am getting this error for line 1 of app.js
Uncaught SyntaxError: Unexpected token import app.js:1
Here is the default generated app.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
You had it mostly wrong, actually -- all wrong.
Let's start with;
However, I would also like to reuse the same code base for a web application.
So this is wrong, the project you are working on is a native project, which uses the component based rendering logic of react, and produces real legit native ui elements for android or iOS.
Even though you are still using "react" this does not mean you can reuse the app in your browser.
The local server that started in a development interface, or a package delivery and update system (packager) for your phone or simulator (in order to access it via wifi network).
That server and the context of it is just a development tool for you.
You should first understand the logic behind tech you are using; https://facebook.github.io/react-native/docs/getting-started.html

Resources