WebView does not render the correct width and does not render at all without a height property on React Native 0.63 - react-native

I use React Native 0.63 on Android with TypeScript, no expo and, worth mentionning, react-native-orientation-locker.
I made an Embed component like this:
const Embed: FC<Props> = ({ embed }: Props) => {
const { width, height } = useDimensions().window
console.log(`WIDTH = ${width}`)
// Return 411
const getSource = (embedCodeOrURI: string): (WebViewSourceUri & string) | (WebViewSourceHtml & string) => {
if (embed.startsWith('http')) {
console.log(`DEBUG > Embed > returned { uri: ${embed}}`)
return { uri: embedCodeOrURI } as WebViewSourceUri & string
}
console.log(`DEBUG > Embed > returned { html: ${embed}}`)
// If I use the test content, I still need to specify the height in the style prop but the width adjust correctly
const test =
'<div style="background-color:red"><p style="font-size:32pt">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p></div>'
// Using the wrapper or not has zero impact on the bug
const withWrapper = `
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="baseDiv" style={max-width: 100%;max-height: 100%}>${embedCodeOrURI}</div>
</body>
</html>
`
const html = withWrapper
return { html } as WebViewSourceHtml & string
}
if (!embed) {
console.log(`ERROR > Embed > embed = ${embed}`)
return null
}
return (
<WebView
originWhitelist={['*']}
source={getSource(embed)}
scalesPageToFit={true}
containerStyle={{ backgroundColor: 'blue', height: 800 }}
allowsFullscreenVideo={true}
onError={(syntheticEvent): void => {
const { nativeEvent } = syntheticEvent
console.warn('ERROR > Embed > WebView error: ', nativeEvent)
}}
onHttpError={(syntheticEvent): void => {
const { nativeEvent } = syntheticEvent
console.warn('ERROR > Embed > WebView http error: ', nativeEvent.statusCode)
}}
onRenderProcessGone={(syntheticEvent): void => {
const { nativeEvent } = syntheticEvent
console.warn('WebView Crashed: ', nativeEvent.didCrash)
}}
onContentProcessDidTerminate={(syntheticEvent): void => {
const { nativeEvent } = syntheticEvent
console.warn('ERROR > Embed > Content process terminated: ', nativeEvent)
}}
startInLoadingState={true}
renderLoading={(): ReactElement => <ActivityIndicator />}
/>
)
}
export default Embed
First strange thing, the Twitter or Instagram embeds I tested displays in 411 width:
Second strange thing, If I use useDimensions().window.width (=411) as a the containerStyle width, this does no change.
...But if I add width=600, the view scale.
Third stange thing, the test html does displays full width if I don't specify a width.
...and will scale out of the screen if I specify 600:
Forth strange thing, if I do not add a height in the container view, the html content don't displays at all.

I solved the issue of the different scales by adding this in the head:
<head>
<meta charset="utf-8">\
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
I still need to specify a height so I currently adjust this manually for each post in the database.

Related

Erorr when trying to create a multiple-choice in React-Native

I am trying to create a simple multiple choice like that
'
use strict';
import React, {
Component,
StyleSheet,
Text,
View
} from 'react-native';
import MultipleChoice from 'react-native-multiple-choice'
class Home extends Component {
render() {
return (
<View style={styles.container}>
<MultipleChoice
options={[
'Lorem ipsum dolor sit',
'Lorem ipsum',
'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.',
'Lorem ipsum dolor sit amet, consetetur',
'Lorem ipsum dolor'
]}
selectedOptions={['Lorem ipsum']}
maxSelectedOptions={2}
onSelection={(option)=>alert(option + ' was selected!')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 60,
margin: 20
},
});
export default Home
But it gives me this erorr when I try to run it : TypeError: undefined is not an object (evaluating '_react.default.PropTypes.array')
Somebody has any idea what the problem could be ?

Failing to alias react-native-linear-gradient to react-native-web-linear-gradient for react native web app

I have a react-native app with a single screen containing a LinearGradient which I am trying to get working as a web app.
When I run the application I have the following error.
./node_modules/react-native-linear-gradient/common.js
C:/myapp/node_modules/react-native-linear-gradient/common.js:6
3 | import type { ElementProps } from 'react';
4 | import { requireNativeComponent, View } from 'react-native';
5 |
> 6 | export default requireNativeComponent('BVLinearGradient');
7 |
8 | export type Point = $Exact<{x: number, y: number}>;
9 | type LinearGradientProps = {
Without the LinearGradient components the app runs perfectly OK. I believe the issue is that that "react-native-linear-gradient" will not work in a Web App.
Note: my version of react-native-web is "0.13.14"
App.js
import React from 'react';
import LinearGradient from 'react-native-linear-gradient';
import { StyleSheet, Text } from 'react-native';
const styles = StyleSheet.create({
drawer: {
flex: 1,
},
});
const GRADIENT_COLORS = ['blue', 'white', 'black'];
export default class App extends React.Component {
render() {
return (
<LinearGradient
colors={GRADIENT_COLORS}
style={styles.drawer}
>
<Text>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum
erat in elit eleifend posuere. Cras interdum sagittis sem non consectetur.
Quisque nec faucibus odio. Phasellus ac ante felis. Nulla facilisis risus nulla,
eget interdum augue pellentesque id. Phasellus pellentesque augue eget porta
fringilla. Vivamus rhoncus scelerisque libero sit amet ullamcorper. Vestibulum
sit amet est ultrices, tristique risus vitae, aliquet ligula. Ut bibendum dignissim
tincidunt. In et tortor ullamcorper, dapibus arcu a, pellentesque velit. Praesent
ornare metus dapibus, tincidunt nulla in, maximus nisl. Ut molestie aliquam mi,
ac molestie purus sagittis eget. Aliquam sit amet lacus quis risus convallis semper.
</Text>
</LinearGradient>
);
}
}
I saw that there is a polyfill for LinearLayout, i.e. "react-native-web-linear-gradient". Therefore it is my understanding I simply install that package and alias the original LinearLayout to this one.
I have installed the following
"react-native-web-linear-gradient": "1.1.1"
"react-app-rewired": "^2.1.6",
"customize-cra": "^1.0.0",
My "config-overrides.js" is :
const {addWebpackAlias} = require('customize-cra');
module.exports = function override(config, env) {
config.module.rules.push(
{
test: /\.js$/,
exclude: /node_modules\/(?!()\/).*/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: ['#babel/plugin-proposal-class-properties'],
},
},
},
);
addWebpackAlias({
'react-native-linear-gradient': 'react-native-web-linear-gradient',
});
return config;
};
Here I am aliasing 'react-native-linear-gradient' to 'react-native-web-linear-gradient'. My understanding is that all imports like
import LinearGradient from 'react-native-linear-gradient';
will be converted into
import LinearGradient from 'react-native-web-linear-gradient';
by webpack when building the web app.
However I am still getting the same error, like its not using the alias.
What do I have wrong.
addWebpackAlias is not imported into the config, you should use the build-in override of custom-cra and refer to its api for webpack config
/* config-overrides.js */
const {
override,
addWebpackAlias,
addBabelPlugins,
addBabelPresets,
babelExclude,
path,
} = require('customize-cra');
module.exports = override(
babelExclude([path.resolve("node_modules")]),
...addBabelPlugins('#babel/plugin-proposal-class-properties'),
...addBabelPresets('#babel/preset-env', '#babel/preset-react'),
addWebpackAlias({
'react-native-linear-gradient': 'react-native-web-linear-gradient',
}),
);
Edit: you can use babelExclude to exclude folder you don't want to transpile

node redis client: correct way to save JavaScript objects in lists

I need some help with the following scenario: I am using redis to store chat messages sent to various rooms:
for(var i = 0; i < 5; i++){
var message = {
"player": "player " + i,
"message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque convallis finibus bibendum. Praesent quis ante vitae est porttitor scelerisque. Vestibulum blandit, urna ac placerat vehicula, orci nunc bibendum sem, vitae condimentum orci purus id nisi.",
"room": "room-1",
"time": new Date()
};
client.lpush(1room-1', JSON.stringify(message), redis.print);
}
I then fetch the last 100 messages:
var args = [ 'room-1', '0', '100' ];
client.lrange(args, function(err, results){
if(err){
console.log(err);
} else {
_.each(results, function(result){
var message = JSON.parse(result);
console.log(message);
});
}
});
I am new to redis and would like to make sure this is the best way of writing and reading for the scenario. I am concerned about the need to stringify the object for write and then parse the reads.
Is this the optimal way of doing this?

Titanium Alloy - How to animate a View from 0 height to "auto"

In Titanium Alloy, I'm looking to animate a View from a height of 0, to a height of "auto" or Ti.UI.SIZE. The View contains a Label, which has a varying amount of text in it that can span over several lines, so I need the View to animate to the height that it needs just to show the Label within. The idea is that you click a button and it animates the View and text to slide open. Similar to the jQuery slideDown animation seen a lot on the web.
The problem I'm having is that if I try to animate to a height of "auto" or Ti.UI.SIZE, the animation doesn't seem to happen at all. Animating to a fixed height works, but I need it to be flexible to contents of the view.
My view
<Button id="toggleBrandInfoBtn" onClick="toggleBrandInfo" title="Show Text" />
<View id="brandInfo" layout="vertical" height="0">
<Label id="brandInfoLabel" text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor."></Label>
</View>
Controller
$.brandInfo.anchorPoint = {x:0, y:0};
$.toggleBrandInfoBtn.addEventListener("click", function () {
$.brandInfo.animate({
anchorPoint: {x:1, y:1},
top: 0,
height: Ti.UI.SIZE,
duration: 1000
});
});
Have you tried a percentage value? This is not necessarily documented but I have had some success with it. Also try a 1% starting value.
$.brandInfo.anchorPoint = {x:0, y:0};
$.toggleBrandInfoBtn.addEventListener("click", function () {
$.brandInfo.animate({
anchorPoint: {x:1, y:1},
top: 0,
height: '100%',
duration: 1000
});
});
As of SDK 3.3.0 this is not possible.
One way around the problem might be to start with brandInfo visible=false and height Ti.UI.SIZE
From that get the view height required for the content and store.
Then as part of your animation sequence set the height to zero, make visible = true and then do the animation to the pre-calculated height stored earlier.
I had the same issue and this module helped me out there:
https://github.com/animecyc/TitaniumAnimator

BuddyPress bbPress unique thread per member

I would like a discussion about each user in one place. Is it possible to automatically assign a unique bbPress thread for each user and have a link to that thread placed in the BuddyPress profile?
my current attempt is to add the following code to the functions.php:
function automatic_user_forum( $user_id ) {
if( !$user_id ) return false;
$post = array(
‘post_title’ => ‘My forum’,
‘post_content’ => ‘This is a forum.’,
‘post_name’ => ‘my-forum’,
‘post_status’ => ‘publish’,
‘post_type’ => ‘forum’,
);
$post_id = wp_insert_post($post);
}
add_action( ‘bp_core_activated_user’, ‘automatic_user_forum’ );
However, it is not working and the site crashes. Any help?
Alternatively I tried the following which doesn't crash but also doesnt create any forum. Whats wrong?
<?php
function bbp_insert_girl_forum() {
$forum_data = array(
'post_parent' => 0, // forum ID
'post_content' => 'Nullam est felis, tempor luctus consequat a, aliquam ut dolor. Proin euismod aliquam ante accumsan cursus. Morbi ornare eros magna, eget sollicitudin turpis fringilla quis. Proin vitae vehicula felis. Fusce non lacus consequat, faucibus nisl sed, consequat dolor.',
'post_title' => 'Test Forum: Loads of Topics for topic Pagination',
);
if(function_exists('bbp_insert_forum')) {
$forum_id = bbp_insert_forum( $forum_data );
}else {
print "insert forum not defined";
}
$topic_data = array(
'post_parent' => $forum_id, // forum ID
'post_content' => 'Proin euismod aliquam ante accumsan cursus. Morbi ornare eros magna, eget sollicitudin turpis fringilla quis. Proin vitae vehicula felis. Fusce non lacus consequat, faucibus nisl sed, consequat dolor.',
'post_title' => 'Gravida facilisis eleifend',
);
if(function_exists('bbp_insert_topic')) {
$topic_id = bbp_insert_topic( $topic_data );
}
else {
print "insert topic not defined";
}
}
add_action( ‘bp_core_activated_user’, ‘bbp_insert_girl_forum’ );
?>
function bbp_insert_girl_forum() {
$forum_data = array(
'post_parent' => 0, // forum ID
'post_content' => 'Nullam ...',
'post_title' => 'Test Forum',
);
if(function_exists('bbp_insert_forum')) {
$forum_id = bbp_insert_forum( $forum_data );
}
}
add_action( 'bp_core_activated_user', 'bbp_insert_girl_forum' );