Using if else statement in renders block in react native - react-native

This is my render function
render () {
return (
<CheckoutView>
<CheckoutActionButton onPress={this.props.navigateSplitTender}><CheckoutActionButtonLabel>Partial Card Payments</CheckoutActionButtonLabel></CheckoutActionButton>
</CheckoutButtonArea>
<CheckoutButtonArea>
{if (this.props.env !== 'Production')
<CheckoutActionButton onPress={this.props.navigateMockPayment}><CheckoutActionButtonLabel>Mock Payments</CheckoutActionButtonLabel>}</CheckoutActionButton>}
</CheckoutButtonArea>
</CheckoutActionArea>
</CheckoutView>
)
}
What I am trying to do is if the environment is not Production, I am trying to navigate the mockpayment page. But it is not showing up, where I am getting worng?

i think you might have forgot to close your condition on the if statement
{if (this.props.env !== 'Production')
you need a curly bracket to close everything up

The <CheckoutActionButton.. is not inside of if block, using shorthand condition is better.
render () {
return (
<CheckoutView>
<CheckoutActionButton onPress={this.props.navigateSplitTender}><CheckoutActionButtonLabel>Partial Card Payments</CheckoutActionButtonLabel></CheckoutActionButton>
</CheckoutButtonArea>
<CheckoutButtonArea>
{this.props.env !== 'Production' && <CheckoutActionButton onPress={this.props.navigateMockPayment}><CheckoutActionButtonLabel>Mock Payments</CheckoutActionButtonLabel>}</CheckoutActionButton>}
</CheckoutButtonArea>
</CheckoutActionArea>
</CheckoutView>
)
}
If it's not working. Try to log this.props.env to make sure it not "Production"

Related

Does Cypress .trigger() and .type() actually trigger an actual keydown event?

We have a small Vue 2 app managing a form and its submission.
In the Vue app, there is a method on the the input field for a credit card expiration date.
<input
v-model="expDate"
type="text"
name="expirDate"
placeholder="MMYY"
#blur="checkExpDate"
#keydown="appendSlash($event)"
/>
We have an appendSlash() method that checks each keydown and adds a slash after the first two digits are typed in:
appendSlash(event) {
if (
event.key === "Backspace" ||
event.key === "Tab" ||
(event.keyCode >= 48 && event.keyCode <= 57)
) {
if (
this.expDate.length === 2 &&
event.key !== "/" &&
event.key !== "Backspace"
) {
this.expDate += "/";
return false;
}
return true;
} else {
event.preventDefault();
return false;
}
This works fine if we manually do this in the browser. However, our QA person has tried to automate this via the following Cypress methods, but the slash never gets added.
cy.get('input').type('0925');
cy.get('input').type('09');
cy.wait(5000);
cy.get('input').type('25');
cy.get('input').trigger('keydown', { keyCode: 48 })
cy.wait(5000);
cy.get('input').trigger('keydown', { keyCode: 57 })
cy.wait(5000);
Does .trigger() and .type() provide a real keyboard event, or is our QA just using the Cypress API incorrectly?
(I understand there is a vue-cypress module available, but we can't use it yet in our infrastructure.)
Yes, it does according to the documentation here.
Also, this is the info you get when you click on the type action in the cypress UI and the action output gets printed to the console:
I heard back from the QA person.
They ended up solving it using .clear() and .invoke().
cy.xpath('//input[#name="expirDate"]').clear().invoke('val', '05/25').trigger('input');
They said they had to clear the field first, then put in the number, and finally trigger an input event. It worked.

$refs are null after route change

I have a keyboard navigation system. When you press ArrowUp or ArrowDown, an event is emitted FROM app.js (best place I found to listen to these keypresses since they need to be system-wide) TO the mounted() in the component.
The Event.$on() INSIDE the mounted() part of the component then calls a function that uses $refs to identify the currently selected item and, when ENTER is pressed, show it's modal.
app.js code (listen to the keypresses):
else if (event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'Enter') {
event.preventDefault()
switch (this.$router.currentRoute.path) {
case "/pedidos":
Event.$emit('navegarSetasPedidos', event.key)
break;
case "/clientes":
Event.$emit('navegarSetasClientes', event.key)
break;
}
}
mounted() section of the component in question:
mounted() {
Event.$on('navegarSetasPedidos', (key) => {this.navegarSetas(key)})
}
function responsible for the navigation (sorry for bad formating, haven't figured how stackoverflow's codeblock thing works yet):
navegarSetas(key) {
if (this.navegacaoSetasAtiva == false) {
this.navegacaoSetasAtiva = true
this.navegacaoAtual = 0
} else if (this.modalAtivado == false && this.navegacaoSetasAtiva == true) {
if (key == 'ArrowDown' && this.navegacaoAtual < this.pedidos.length - 1) {
this.navegacaoAtual++
let elementoSelecionado = this.$refs['pedido'+this.navegacaoAtual][0].$el
let boundaries = elementoSelecionado.getBoundingClientRect()
if (boundaries.top < 0 || boundaries.top > (window.innerHeight || document.documentElement.clientHeight)){
elementoSelecionado.scrollIntoView({behavior: 'smooth'})
}
} else if (key == 'ArrowUp' && this.navegacaoAtual <= this.pedidos.length && this.navegacaoAtual > 0) {
this.navegacaoAtual--
let elementoSelecionado = this.$refs['pedido'+this.navegacaoAtual][0].$el
let boundaries = elementoSelecionado.getBoundingClientRect()
if (boundaries.top < 0 || boundaries.top > (window.innerHeight || document.documentElement.clientHeight)){
elementoSelecionado.scrollIntoView({behavior: 'smooth'})
}
} else if (key == 'Enter') {
let pedidoSelecionado = this.pedidos[this.navegacaoAtual].id
Event.$emit('changeShow', pedidoSelecionado)
}
}
This works very well the first time it is acessed. The problem is, if I change the current route to show another component and then return to the previous component, I get a lot of "this.$refs['pedido'+this.navegacaoAtual][0].$el is undefined" errors, but the system still works normally, albeit erratically.
The funny thing is: if I console log "this.$refs['pedido'+this.navegacaoAtual][0].$el is undefined", I'll get an EMPTY log before the errors, then ANOTHER one right below it, this time, not empty.
Everywhere else I've searched this says that the problem is due to how Vue re-renders things, and that I'm calling this event BEFORE it's rendered, which shouldn't be possible since I'm calling it inside mounted().
Any help is greatly appreciated, thank you!
Turns out, after a LOT of searching, the Event.$on event setters also work as the normal JavaScript ones (which makes a lot of sense now that I'm thinking about it)—meaning that you have to destroy them whenever your component is unmounted (aka Destroyed).
Even though VUE Dev Tools was picking only one event after the re-route, it was still firing two (seen through console.log() returning one empty value, a bunch of errors, and another value with filled array AFTER the errors).
The solution to this was simply adding Event.$off('eventName') on the destroyed() function of the component.

Error: Maximum update depth exceeded. React Native

I try to setState in compenetDidUpdate but it shows error infinite loop. Got any solution? Originally I put the setState in a function but also face this error. I am using class component code
componentDidUpdate(){
if(isEmpty(this.props.AESDetail) == false){
if(this.props.AESDetail.length != 0){
if(this.props.APIESDetail.length != 0){
if(this.props.APIESDetail.Focus != null){
this.setState({
gotFocusApies: true
})
}
}
}
}
}
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
It looks like you might just need one additional test to make sure gotFocusApies isn't already true.
These if statements are also probably better off combined into one.
Note: list.length != 0 can typically be replaced with list.length or !!list.length.
componentDidUpdate() {
if (
isEmpty(this.props.AESDetail) == false &&
this.props.AESDetail.length &&
this.props.APIESDetail.length &&
this.props.APIESDetail.Focus != null &&
!this.state.gotFocusApies
) {
this.setState({ gotFocusApies: true });
}
}

React Native - Derectional Pad support Android TV App

I would want to build an Android TV app using React-Native. I have followed up the recommendation on this document: Building For TV Devices.
After, update the AndroidManifest.xml file I run the application using the command line - react-native run android. The app running without any issue; however, I tried to use the Directional-pad option from android emulator TV (720p) API 23 emulator and it didn't work. I was expecting to catch the event listed on the code below and write to the console respective test for each event. On the other hand, even the component that was used for text didn't get highlighted either focus on when I try to navigate using Directional-pad.
I am reaching out to the community to see if someone had this issue in the past and what was your issue and what you have done to resolve it? Also, as I am listing the steps below, if you could let me know if I missing something?
Please, let me know if you need any extra information in order to help me.
react-native init Dpad
cd Dpad
Update code based on - Building For
TV Devices
Start Android TV (720p) API 23 emulator.
react-native run-android
ANNEX:
Android TV (720p) API 23
Here is the code:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Channel from '../channel/channel.component';
import styles from './presentation.component.styles';
var TVEventHandler = require('TVEventHandler');
export default class Grid extends Component {
constructor(props){
super(props);
this.state = {
command: 'undefined'
}
}
setcomand( command) {
this.setState( () => { return { command: command }; });
}
_tvEventHandler: null;
_enableTVEventHandler() {
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function(cmp, evt) {
if (evt && evt.eventType === 'right') {
setcomand('Press Right!');
} else if(evt && evt.eventType === 'up') {
setcomand('Press Up!');
} else if(evt && evt.eventType === 'left') {
setcomand('Press Left!');
} else if(evt && evt.eventType === 'down') {
setcomand('Press Down!');
}
});
}
_disableTVEventHandler() {
if (this._tvEventHandler) {
this._tvEventHandler.disable();
delete this._tvEventHandler;
}
}
componentDidMount() {
this._enableTVEventHandler();
console.warn("component did mount");
}
componentWillUnmount() {
this._disableTVEventHandler();
console.warn("component Will Unmount");
}
render() {
return (
<View style={styles.container}>
<Text>{this.state.command}</Text>
<Channel name="Globo" description="Its brazilian TV channles for news"/>
<Channel name="TVI" description="Its Portuguese TV channles for news"/>
<Channel name="TVI" description="Its Portuguese TV channles for news"/>
</View>
);
}
}
I'm also struggling with this problem for a month. Still can't find help/solution.
I testing this on Android Studio Emulator and also on few real android TV boxes with real remote d-pads.
I still can't figure out if it's React Native problem (bug) or Android TV devices don't emit response (keyCode) on directional d-pad arrows.
I can reproduce events like: focus, blur, select, fastForward, playPause, rewind, but no way to get events like e.g. "left".
I search a lot of google and other sites, you are first one who struggling with same issue.
I feel like no one cares about Android TV in React-Native.
You can also comment my Issue thread on React-Native github page.
https://github.com/facebook/react-native/issues/20924
I hope we figure it out soon.
Cheers
I was not able to verify that Directional-pad works with react-native. That was my goal of this demo. I am learning to build android Tv using react-native and so far Directional-pad it's being a big challenge given that TV user won't use touch screen event.
However, I couldn't find out why my app was not responding to the Directional-pad keyboard (left, right, up and down). There was no code error.
Have you tried to use Directional-pad to navigate on your react-native app?
Thank you,
Dave -
I decided to develop Android TV app using React Native because the video that react-native team shared - [https://www.youtube.com/watch?v=EzIQErHhY20] and the tutorial page [https://facebook.github.io/react-native/docs/building-for-apple-tv]. I think that's everything we have; other than that we won't get further support.
GOOD NEWS - I have started a new project from scratch using react native version 0.57.0, node version V10.7.not and **npm Version 4.6.1. Also, for navigation, I am using react-navigation version 2. I was able to see that my Directional-pad emulator was working, however, I was not able to see the focus on the element that I am navigating (left, right, down, up).
I will be working to see how I can fix the focus issue.
Let's keeping share our progress and feel free to reach out.
Thank you,
Justimiano Alves
use this code and u can see the console on debugger
_tvEventHandler: any;
_enableTVEventHandler() {
var self = this;
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function (cmp, evt) {
console.log("kcubsj"+evt.eventType)
if (evt && evt.eventType === 'right') {
console.log('right');
} else if (evt && evt.eventType === 'up') {
console.log('up');
} else if (evt && evt.eventType === 'left') {
console.log('left');
} else if (evt && evt.eventType === 'down') {
console.log('down');
} else if (evt && evt.eventType === 'select') {
//self.press();
}
});
}
_disableTVEventHandler() {
if (this._tvEventHandler) {
this._tvEventHandler.disable();
delete this._tvEventHandler;
}
}
componentDidMount() {
this._enableTVEventHandler();
}
componentWillUnmount() {
this._disableTVEventHandler();
}
I have really good news about support for D-Pad arrow events (up, down, left, right).
It turned out that one of Android TV contributor for react-native is person from my country. I reach out contact with him and tell about this problem. He check that out and actually, there is missing code for that.
He made pull request to support that in react-native. It should be fixed in one of upcoming new version releases (he said it might took about month).
Temporarly I know how to handle this (add code and recompile java files), I already tested it and its work great. All events now working. If you really need that support now and don't want to wait, I can share how to do that.
Cheers
Yes. I would like to see your solution because I am able to navigate using the D-pad but I couldn't see which element I am navigating to. I need to highlight or show focus on the element that I navigating to.
Having console.log inside the TVEventHandler callback seems to break it when running without remote js debugger on.
I have observed that D-pad does not work if there is no focusable component. To solve this, I have placed a transparent touchable opacity component on my screen. After that D-pad started working. My code for D-pad key event is given below:
enableTVEventHandler() {
this.tvEventHandler = new TVEventHandler();
this.tvEventHandler.enable(this, (cmp, { eventType, eventKeyAction }) => {
// eventKeyAction is an integer value representing button press(key down) and release(key up). "key up" is 1, "key down" is 0.
if (eventType === 'playPause' && eventKeyAction === 0)
{
console.log('play pressed')
}
else if(eventType === 'fastForward' && eventKeyAction === 0){
console.log('forward pressed')
}
else if (eventType === 'rewind' && eventKeyAction === 0){
console.log('rewind pressed')
}
else if (eventType === 'select' && eventKeyAction === 0)
{
console.log('select pressed')
}else if(eventType === 'left' && eventKeyAction === 0){
console.log('left pressed')
}
else if(eventType === 'right' && eventKeyAction === 0){
console.log('right pressed')
}
else if(eventType === 'up' && eventKeyAction === 0){
console.log('up pressed')
}
else if(eventType === 'down' && eventKeyAction === 0){
console.log('down pressed')
}
});
}

Apply Prestashop Cart to custom Hook

First let me explain myself. I'm new to Prestashop Development, I've a background using Wordpress. The thing is, I'm trying to hook 'blockcart.php' to my custom hook 'HOOK_SHOPPINGBAG'. I have tried a lot and after a couple of hours I have decided to just ask the question here.
First I have created the Hook inside ps_hook inside the Prestashop Database. This hook is functioning and Prestashop reads it. After that I have added my new hook to FrontController.php, the code is shown below:
public function initContent()
{
$this->process();
if (!isset($this->context->cart))
$this->context->cart = new Cart();
if (!$this->useMobileTheme())
{
// These hooks aren't used for the mobile theme.
// Needed hooks are called in the tpl files.
$this->context->smarty->assign(array(
'HOOK_HEADER' => Hook::exec('displayHeader'),
'HOOK_TOP' => Hook::exec('displayTop'),
'HOOK_SHOPPINGBAG' => Hook::exec('displayShoppingBag'),
'HOOK_LEFT_COLUMN' => ($this->display_column_left ? Hook::exec('displayLeftColumn') : ''),
'HOOK_RIGHT_COLUMN' => ($this->display_column_right ? Hook::exec('displayRightColumn', array('cart' => $this->context->cart)) : ''),
));
}
else
$this->context->smarty->assign('HOOK_MOBILE_HEADER', Hook::exec('displayMobileHeader'));
}
I also have added the Hook to the second bunch of lines inside FrontController.php:
// Call hook before assign of css_files and js_files in order to include correctly all css and javascript files
$this->context->smarty->assign(array(
'HOOK_HEADER' => $hook_header,
'HOOK_TOP' => Hook::exec('displayTop'),
'HOOK_SHOPPINGBAG' => Hook::exec('displayShoppingBag'),
'HOOK_LEFT_COLUMN' => ($this->display_column_left ? Hook::exec('displayLeftColumn') : ''),
'HOOK_RIGHT_COLUMN' => ($this->display_column_right ? Hook::exec('displayRightColumn', array('cart' => $this->context->cart)) : ''),
'HOOK_FOOTER' => Hook::exec('displayFooter')
));
I want to show the Cart inside header.tpl so I have added the Hook to this file:
<div class="shoppingbag">
{$HOOK_SHOPPINGBAG}
</div>
To make sure Blockcart.php can be hooked to my new hook I have added the following line to blockcart.php:
public function hookShoppingBag($params) {
return $this->hookheader($params, 'displayShoppingBag');
}
I've already tried so many things, but when I try to Hook the module to the new Hook it keeps telling me "This modules can't transplant to this hook!"
Maybe I have just made some stupid mistakes, but anyway I hope you guys can help me. Thanks!
I assume you need a custom hook for blockcart module to be placed somewhere.
This is how to achieve it through Presta's custom hook way.
|| $this->registerHook('shoppingBag') == false
Add this to the module's install method.
public function install()
{
if (
parent::install() == false
|| $this->registerHook('top') == false
|| $this->registerHook('header') == false
|| $this->registerHook('actionCartListOverride') == false
|| Configuration::updateValue('PS_BLOCK_CART_AJAX', 1) == false
|| Configuration::updateValue('PS_BLOCK_CART_XSELL_LIMIT', 12) == false)
|| $this->registerHook('shoppingBag') == false
return false;
return true;
}
Create a public method hookShoppingBag like this.
public function hookShoppingBag($params)
{
return $this->hookProductActions($params);
}
To hook it to any tpl use this.
<div class="shoppingbag">
{hook h='presetWishlist'}
</div>