How to pass data from vanilla JavaScript to React functional comonent

I’m trying to update (setState) a React functional component from within “regular” (vanilla) JavaScript.

I searched through StackOverflow but all the answers deal with passing data from React to (vanilla) JavaScript, and not the other way around.

Let’s take the example from the docs:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

To render it in JavaScript, I do:

<script>
    let example = ReactDOM.render(
        <Example />,
        document.getElementById('example-wrapper')
    );
</script>

Now suppose I want to manually update the count from the vanilla JavaScript code, outside of react. Like:

<script>
    function updateExampleCount(newCount) {
        example.setCount(newCount);   // ???
    }
</script>

I can’t access the component state, as setCount is a private variable inside the function, and example returned from render is null.

If I use a class component, then render returns a reference to the component and then I can call example.setState. But I prefer not to convert my component into a class if I can avoid it.

The docs for render say:

Render a React element into the DOM in the supplied container and return a reference to the component (or returns null for stateless components).

But my component does have a state (count), it just doesn’t recognize it.
If it’s not possible to use the return value from render, is there another way to “get” the component and then use setCount (or some other way to set the state)?

Or do I just have to use a class component for this?

Thanks.

Uncaught Error: Unable to find node on an unmounted component (react-dom)

i’m writing a webapp using mern stack and while i’m writing the code i got this error and have no idea where this error are occurred.
details about error down below

Uncaught Error: Unable to find node on an unmounted component.
at findCurrentFiberUsingSlowPath (react-dom.development.js:4303)
at findCurrentHostFiber (react-dom.development.js:4465)
at findHostInstanceWithWarning (react-dom.development.js:25389)
at Object.findDOMNode (react-dom.development.js:26067)
at Trigger._this.getRootDomNode (index.js:237)
at Trigger._this.attachParent (index.js:331)
at index.js:349
at callRef (raf.js:36)
at raf.js:40

and this is the only file i change before change this whole application work properly i think this is the file that above error occurred

import React, { Fragment, useState, useEffect } from "react";
import Pagination from 'react-js-pagination';
import { useParams } from 'react-router-dom';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';

import MetaData from "./layout/MetaData";
import Product from "./product/Product";
import Loader from "./layout/Loader";

import { useDispatch, useSelector } from "react-redux";
import { useAlert } from "react-alert";
import { getProducts } from "../actions/productActions";

const { createSliderWithTooltip } = Slider
const Range = createSliderWithTooltip(Slider.Range)

const Home = () => {
const [currentPage, setCurrentPage] = useState(1)
const [price, setPrice] = useState([1, 1000])
const [category, setCategory] = useState('')

const categories = [
    'books',
    'pencils',
    'cuters',
    'pastles',
    'Electronics',
    'Headphones',
    'Accessories',
    'Cameras',
    'Laptops',
    'Food'
]

const alert = useAlert();
const dispatch = useDispatch();
const params = useParams();

const { loading, products, error, productCount, resPerPage } = useSelector(
    (state) => state.products
);

const keyword = params.keyword

useEffect(() => {
    if (error) {
        return alert.error(error);
    }

    dispatch(getProducts(keyword, currentPage, price, category));

}, [dispatch, alert, error, keyword, currentPage, price, category]);

function setCurrentPageNo(pageNumber) {
    setCurrentPage(pageNumber)
}

return (
    <Fragment>
        {loading ? (
            <Loader />
        ) : (
            <Fragment>
                <MetaData title={"Home page"} />

                <h1 id="products_heading">Latest Products</h1>

                <section id="products" className="container mt-5">
                    <div className="row">
                        {keyword ? (
                            <Fragment>
                                <div className="col-6 col-md-3 mt-5 mb-5">
                                    <div className="px-5">
                                        <Range
                                            marks={{
                                                1: `$1`,
                                                1000: `$1000`
                                            }}
                                            min={1}
                                            max={1000}
                                            defaultValue={[1, 1000]}
                                            tipFormatter={value => `$${value}`}
                                            tipProps={{
                                                placement: "top",
                                                visible: true
                                            }}
                                            value={price}
                                            onChange={price => setPrice(price)}
                                        />

                                        <hr className="my-5" />

                                        <div className="mt-5">
                                            <h4 className="mb-3">
                                                Categories
                                            </h4>

                                            <ul className="pl-0">
                                                {categories.map(category => (
                                                    <li
                                                        style={{
                                                            cursor: "pointer",
                                                            listStyleType: "none"
                                                        }}
                                                        key={category}
                                                        onClick={() => setCategory(category)}
                                                    >
                                                        {category}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    </div>
                                </div>

                                <div className="col-6 col-md-9">
                                    <div className="row">
                                        {products.map((product) => (
                                            <Product key={product._id} product={product} col={4} />
                                        ))}
                                    </div>
                                </div>
                            </Fragment>
                        ) : (
                            products.map((product) => (
                                <Product key={product._id} product={product} col={3} />
                            ))
                        )}

                    </div>
                </section>

                {resPerPage <= productCount && (
                    <div className="d-flex justify-content-center mt-5">
                        <Pagination
                            acvitePage={currentPage}
                            itemsCountPerPage={resPerPage}
                            totalItemsCount={productCount}
                            onChange={setCurrentPageNo}
                            nextPageText={'Next'}
                            prevPageText={'Prev'}
                            firstPageText={'First'}
                            lastPageText={'Last'}
                            itemClass="page-item"
                            linkClass="page-link"
                        />
                    </div>
                )}
            </Fragment>
        )}
    </Fragment>
);
};

export default Home;

and this is the git repo if you want more info check last commit

Why is my Swiper render buggy at the first time render using React

I’m using React and trying to fetch some of my anime into the home banner using Swiper

I don’t know why when I refresh my page, it’ll only render at half of the swiper.

Here’s how it display:

First display

However, if I press the next or back button, it’ll display normally again.

Working fine after next/previous button being pressed

Here’s my code in my Home Component:

import { useState, useEffect } from "react"
import ReactHlsPlayer from 'react-hls-player';
import './home.css'
import { supabase } from '../../supabaseClient'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Pagination,Navigation } from 'swiper';
import 'swiper/css'

SwiperCore.use([Pagination,Navigation]);
function Home(){
    useEffect(async ()=>{
        fetchAnime()
    }, [])
    const [animeDetail, setAnimeDetail] = useState([])
    async function fetchAnime() {
        const { data } = await supabase
            .from ('anime')
            .select ()
            setAnimeDetail(data)
    }

    return (
        <>
        <div className="spacer">
            &nbsp;
        </div>
        <div className="home-section">
            <h2>Home Page</h2>
            <Swiper 
            centeredSlides={true}
            slidesPerView={7}
            spaceBetween={10}
            loop={true}
            pagination={false} 
            navigation={true} className="mySwiper">
                {animeDetail.map((element, i)=> 
                    (
                    <SwiperSlide key = {i}><img src={element.anime_image}/></SwiperSlide>
                    )
                    )}

            </Swiper>
        </div>
        </>
    )

}
export default Home

And here’s my Home CSS, sorry if it’s a bit messy, I’m still trying it here and there, but I’m stuck.

  .swiper {
    width: 100%;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
  }
  .swiper-wrapper{
    width: 100%
  }
  .swiper-slide {
    text-align: center;
    font-size: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 280px;
  }
  .swiper-slide img {
    display: block;
    box-sizing: border-box;
    border: none;
    max-height: 350px;
    min-height: 350px;
    -o-object-fit: cover;
       object-fit: cover;
    transition: all .3s ease;
    opacity: 0.5
  }

  .swiper-slide-active {
    transform: scale(1.2);
    z-index: 2
  }
  .swiper-slide-active img{
    transition: all .3 ease;
    opacity: 1
  }

And if someone figures it out, please help me a bit, I tried to whenever the item in the middle is in active, it’ll pop out bigger, but I can’t do it with transform: scale(number) – I have tried it (It does get bigger when it’s active but it doesn’t display bigger at the height, I haven’t figured it out some ways at the moment)

How can I half the array

I am learning to code and I am trying out this javascript object method course. I am currently stuck on this method. I want to have the array with three different numbers(10,20,5) to be /2. I do not understand why it is returning NaN. Thank you for reading.

shirtPrice = 10
jeanPrice = 20
shoePrice = 5

shoppingList = [shirtPrice,jeanPrice,shoePrice];

const shoppingDiscountDay = {
  discountedItems: {
    calculateItemsDiscount() {
        return shoppingList/2; //return NaN
    },
  }
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());

Can a navbar and a jumbotron share the same background image?

I know it is possible to set the body{background-image) while having them both be transparent. But using this method I cannot set the background-color for the rest of the website.

Is it possible, Using Bootstrap, for the navbar and the jumbotron to share a backround image, while the rest of the website can use a background-color?

How to combine map and clamp function together

There are two functions

const clamp = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a) + c

const c = map(-50, 0, 1, 0, 100)
const _c = clamp(c, 0, 1)
console.log(_c, c)

Is there any way that the two function could be combined, something like

const _c = map(-50, 0, 1, 0, 100, {clamp: true})

so that I don’t need copy parameters from the map function to get the new value within the parameters range.

Problem in rendering ejs template with Express

I am using Node.js together with Express and EJS.

Below is my code:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, 'public');
app.use(express.static(publicPath));
//app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/form_get.html', (req, res) => {
    res.sendFile(__dirname + "/" + "form_get.html")
})

app.get('/process_get', (req, res) => {

    console.log(req.query.first_name);
    res.render(path.join(__dirname+'/views/thankyou.ejs'), { name: req.query.first_name});
    
})

var server = app.listen(3000, () => {
    
    var host = server.address().address;
    var port = server.address().port;
    console.log(`Example app listening at ${host}:${port}`);
})

I get the following error message:

Error: Failed to lookup view “…/views/thankyou.ejs” in views directory “…/mysql/views”

What ca be the problem?

facing problem while converting to class to function component

here I have tried to convert code into function component but I am getting to much error pls help me out to convert this code,thank in advance.

import React, { Component, Fragment } from "react";
import {
  TouchableOpacity,
  Text,
  View,
  KeyboardAvoidingView,
  Modal,
  TextInput,
  Platform,
  Keyboard,
  Dimensions,
  ScrollView,
  StatusBar,
  SafeAreaView,
} from "react-native";
import QRCodeScanner from "react-native-qrcode-scanner";
import styles from "./scanStyle";
import AppStore from "../../stores/AppStore";
import { handleScreenNavigation } from "../../utils/NavigationService";
import Theme from "../../utils/Theme";
import LinearGradient from "react-native-linear-gradient";
import CardView from "react-native-cardview";
import Scanstore from "../../stores/Scanstore";
import Toast from 'react-native-simple-toast';
import { Screen } from "../../components/common/Screen";
import { UniversalNavigationHeader } from "../../components/common/NavigationHeader";
import Iconpack from "../../utils/Iconpack";
// import { ScrollView } from "react-native-gesture-handler";

const hRem = AppStore.screenHeight / 812;
const wRem = AppStore.screenWidth / 375;


const STATUSBAR_HEIGHT = StatusBar.currentHeight;

const totp = require("totp-generator");

let b32_regex = /^[a-zA-Z2-7]+=*$/;



class Scan extends Component {
  constructor(props) {
    super(props);
    this.state = {
      scan: false,
      ScanResult: false,
      result: null,
      isShow: false,
      textName: "",
      secretKey: "",
      backupCode: "",
      isBackUpCode: true,
      textInputHighlight: null,
      textInputHighlight2: null,
      textInputHighligh3: null,
      value: "",
      height: 0,
      updateHeightSecretKey: 0,
      platformUri:"",
      styleChange:false,
      keyboardState: 'closed'
    };
  }

  componentDidMount() {
    if(this.props.route.params.edit){
    //   console.log("Appstore.userPin*******************",   this.props.route.params.index,
    //   this.props.route.params.edit,
    //  this.props.route.params.otpFrom,
    //   this.props.route.params.backUpCode,
    //   this.props.route.params.friendlyName)
      this.setState({  secretKey:this.props.route.params.secretKey,
        platformUri :this.props.route.params.otpFrom,
        textName : this.props.route.params.friendlyName ,
        backupCode :  this.props.route.params.backUpCode,
        isBackUpCode: this.props.route.params.backUpCode.length>0?false:true,
        isShow:true
      })
    }
  
    // this.setState({ isShow: true, secretKey: "fsdfsfsf",platformUri:"fdsfsffs" });

    //let data = base32.decode("otpauth://totp/Google%3Arakesh.s%40catalystmedia.io?secret=tqskd2aiylctmid2vzi4lirnuhbshqem&issuer=Googlethe");
    // Keys provided must be base32 strings, ie. only containing characters matching (A-Z, 2-7, =).
    // var hotp = require('hotp')
    // var key = 'tqskd2aiylctmid2vzi4lirnuhbshqem'
    // var counter = 0
    // var tokenhotp = hotp(key, counter, { digits: 6 })
    // // var tokentotp = hotp.totp( key, { digits: 6 })//converting hotp to totp
    // // console.log("totp same---> ", tokentotp)
    // console.log("hotp same ---> ", tokenhotp)
    // console.log("totp diff--->", token);
    // // this.otpList()
    // AppStore.incrementCount()
  }

  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

  _keyboardDidShow = () => {
    this.setState({
        keyboardState: 'opened'
    });
  }

  _keyboardDidHide = () => {
    this.setState({
        keyboardState: 'closed',
        styleChange:false

    });
    console.log("console,console")
  }

  handleCreate = () => {
    console.log(this.state.secretKey,"---------------->",b32_regex.exec(this.state.secretKey))
    if((this.state.secretKey.length>0) && (b32_regex.test(this.state.secretKey) && (this.state.secretKey.length % 8) === 0) ){
      // console.log("----->",AppStore.secretKeyAdded)
      if (AppStore.secretKeyAdded){

        Scanstore.addNewKeyAuthenticator(
          this.state.secretKey,
          this.state.platformUri !== undefined ?this.state.platformUri:"",
          this.state.textName,
          this.state.backupCode
        );
      } else {
        
        Scanstore.setKeyAuthenticator(
          this.state.secretKey,
          this.state.platformUri !== undefined ?this.state.platformUri:"",
          this.state.textName,
          this.state.backupCode
        );
      }
      Scanstore.fetchSecretKeyArray();
    }
    

    else if(this.state.secretKey.length===0){
      // console.log("enter valid")
      Toast.show("Please enter the Secret Key", Toast.LONG);
    }
    else{
      Toast.show("Please enter valid Secret Key", Toast.LONG);
    }

  };

  updateSize = (height) => {
    this.setState({
      height,
    });
  };

  updateSizeSecretKey = (updateHeightSecretKey) => {
    this.setState({
      updateHeightSecretKey,
    });
  };

  bottomModal = () => {
    return (
      <View style={styles.modalStyle}>
        
        <LinearGradient
          start={{ x: 0, y: 0.3 }}
          end={{ x: 0, y: 1.2 }}
          colors={["#020A13", "#000000"]}
          style={styles.modalContent}
        >
        
          <TouchableOpacity
            onPress={() => this.setState({ isShow: false })}
            style={styles.topBar}
          />

<View style={{height: this.state.styleChange ? 200 :"100%",paddingHorizontal:20 }} >
  <ScrollView>
          <CardView
            cardElevation={8}
            cardMaxElevation={2}
            cornerRadius={15}
            style={[
              {
                shadowColor: this.state.textInputHighlight,
              },
              styles.friendlyNameCard,
            ]}
          >
            <TextInput
              style={[styles.input, styles.mod0]}
              placeholderTextColor={Theme.white_color}
              onFocus={() => {
                this.setState({
                  textInputHighlight: Theme.hightLightColor,
                  textInputHighlight2: null,
                  textInputHighligh3: null,
                  styleChange:true
                });
              }}
              onBlur={()=>{
                this.setState({styleChange:false})
              }}
              onChangeText={(value) => {
                this.setState({ textName: value });
              }}
              onSubmitEditing={Keyboard.dismiss}
              value={this.state.textName}
              placeholder={"Friendly Name"}
            />
          </CardView>

          <CardView
            cardElevation={8}
            cardMaxElevation={2}
            cornerRadius={15}
            style={[
              {
                shadowColor: this.state.textInputHighlight2,
              },
              styles.secretKeyStyle,
            ]}
          >
            <TextInput
              style={[
                styles.input,
                {
                  maxHeight: Platform.OS == "android" ? 76 : 44,
                  height:Platform.OS == "android"?this.state.updateHeightSecretKey :44,
                },
              ]}
              placeholderTextColor={Theme.white_color}
              editable={true}
              multiline={true}
              onFocus={() => {
                this.setState({
                  textInputHighlight2: Theme.hightLightColor,
                  textInputHighlight: null,
                  textInputHighligh3: null,
                  styleChange:true
                });
              }}
              onChangeText={(value) => {
                this.setState({ secretKey: value });
              }}
              onContentSizeChange={(e) =>
                this.updateSizeSecretKey(e.nativeEvent.contentSize.height)
              }
              value={this.state.secretKey}
              onSubmitEditing={Keyboard.dismiss}
              placeholder={"Secret Key"}
            />
          </CardView>

          {this.state.isBackUpCode ? (
            <TouchableOpacity
              style={styles.backUp}
              onPress={() => {
                this.setState({ isBackUpCode: false });
              }}
            >
              <Text style={[styles.backUpText,{marginLeft:10 }]}>Want to add Backup Codes?</Text>
            </TouchableOpacity>
          ) : (
            <View style={styles.backUp}>
              <Text
                style={{ ...Theme.encodeSansReg15, color: Theme.white_color,marginLeft:10 }}
              >
                Enter Backup Codes
              </Text>
              <CardView
                cardElevation={8}
                cardMaxElevation={2}
                cornerRadius={15}
                style={[
                  {
                    shadowColor: this.state.textInputHighligh3,
                  },
                  styles.backUpCodeStyle,
                ]}
              >
                <TextInput
                  style={[
                    styles.input,
                    {
                      maxHeight: Platform.OS == "android" ? 102 : 70,
                      height:Platform.OS == "android"?this.state.height: 70,
                    },
                  ]}
                  placeholderTextColor={Theme.white_color}
                  editable={true}
                  multiline={true}
                  onFocus={() => {
                    this.setState({
                      textInputHighligh3: Theme.hightLightColor,
                      textInputHighlight: null,
                      textInputHighlight2: null,
                      styleChange:true
                    });
                  }}
                  onChangeText={(value) => {
                    this.setState({ backupCode: value });
                  }}
                  onContentSizeChange={(e) =>
                    this.updateSize(e.nativeEvent.contentSize.height)
                  }
                  onSubmitEditing={Keyboard.dismiss}
                  value={this.state.backupCode}
                  placeholder={"Backup Code"}
                />
              </CardView>
            </View>
          )}
<View style={{flexDirection:"row", justifyContent:"space-around",alignItems:"center",marginTop:40,marginBottom:AppStore.isAndroid?20:0}}>
          <TouchableOpacity
            style={styles.createButton}
            onPress={() => {
              if(this.props.route.params.edit){

                Scanstore.editElement( 
                  this.props.route.params.index ,
                  this.state.secretKey,
                  this.state.platformUri ,
                  this.state.textName ,
                  this.state.backupCode 
              )
              this.setState({ isShow: false, styleChange:false });
              Scanstore.fetchSecretKeyArray();
              Toast.show("Updated Successfully.", Toast.LONG);

              }
              else{
                this.handleCreate();
                this.setState({ isShow: false, styleChange:false });
              }
              


            }}
            // onLongPress={() => this.setState({ scan: false })}
          >
            <Text style={[styles.tapText, { fontWeight: "600" }]}>{this.props.route.params.edit?"Update":"Create"}</Text>
          </TouchableOpacity>

          <TouchableOpacity
            // style={{ marginTop: 25 }}
            
            onPress={() => 
              {this.setState({ isShow: false, styleChange:false }) 
          console.log("87887787")
            }
          }
            onLongPress={() => this.setState({ scan: false })}
          >
            <Text style={styles.cancelButton}>Cancel</Text>
          </TouchableOpacity>
         </View>
         </ScrollView>

         </View>
        </LinearGradient>
    
      </View>
    );
  };

  onSuccess = (e) => {
    const check = e.data.substring(0, 7);
    console.log("check", check);
    console.log("scanned data ->    " + e.data + "      the whole bunch of data -> ");
    let fetchedData = e.data;
    let secretKey,platformUri;
    if (fetchedData.includes("totp")) {
      secretKey = fetchedData.split("=");
      platformUri = secretKey[2]
      console.log("------------", secretKey);

      secretKey = secretKey[1].split("&");

      // const totpGen = ;
      // let lengthId = AppStore.rData.length;

      // AppStore.addTotp({
      //   id: lengthId,
      //   title: secretKey[0],
      //   otpFrom:platform,
      // });
    }

    // console.log("what the hell", AppStore.deviceIdInfo);

    this.setState({
      result: e,
      scan: false,
      ScanResult: true,
    });
    if (e.data.includes("totp") ) {
      // handleScreenNavigation("OtpScreen", {})
      this.setState({ isShow: true, secretKey: secretKey[0],platformUri:platformUri });
    }
    else if(e.data.includes("hotp")) {
      Toast.show("Something went wrong", Toast.LONG);

    } else {
      Toast.show("Please scan valid QR", Toast.LONG);
handleScreenNavigation("MainAdd")
    }
  };

  scanAgain = () => {
    this.setState({ scan: true, ScanResult: false });
  };

  render() {
    const { height } = this.state;

    let newStyle = {
      height,
    };
    let newStyleSecretKey = {
      height,
    };
    return (
      <SafeAreaView>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : null}
        style={{ flex: 1 }}
      >
           {/* <Screen
            style={styles.mod1}
            statusBar={"light-content"}
            variant={true}
            showMenu={false}
            onNavigate={this.props.navigation}
          >
                 <UniversalNavigationHeader
                hideBack={false}
                goBack={this.props.navigation.goBack}
              /> */}
        <View style={styles.scrollViewStyle}>
          <Fragment>
            {true && (
              <QRCodeScanner
                reactivate={false}
                showMarker={true}
                ref={(node) => {
                  this.scanner = node;
                }}
                cameraStyle={styles.cameraView}
                onRead={this.onSuccess}
          //       topContent={
          //         <View style={{zIndex:9999,width:AppStore.screenWidth,marginTop:Platform.OS === 'ios'?STATUSBAR_HEIGHT:0 }}>
          // <TouchableOpacity
          //   underlayColor={"none"}
          //   style={{ padding:  20, }}
          //   onPress={() => this.props.navigation.goBack()}
          // >
          //   <Image
          //     style={{ width: wRem * 12, height: hRem * 21, }}
          //     source={Iconpack.GLOBAL_BACK_BUTTON}
          //   />
          // </TouchableOpacity>                  
          // </View>
          //       }
                bottomContent={
                  <View style={styles.bottomContainer}>
                    <TouchableOpacity
                      style={styles.tapStyle}
                      onPress={() => this.setState({ isShow: true })}
                      onLongPress={() => this.setState({ scan: false })}
                    >
                      <Text style={styles.tapText}>Have a Key? Tap Here</Text>
                    </TouchableOpacity>
                  </View>
                }
              />
            )}
          </Fragment>

          <Modal
            animationType="slide"
            transparent={true}
            visible={this.state.isShow}
            onRequestClose={() => {
              this.setState({ isShow: false });
            }}
          >
            <KeyboardAvoidingView
              behavior="position"
              enabled
              // style={{paddingBottom:30}}
            >
              {this.bottomModal(newStyle, newStyleSecretKey)}
            </KeyboardAvoidingView>
          </Modal>
          {/* </View> */}
        </View>
        {/* </Screen> */}
      </KeyboardAvoidingView>
      </SafeAreaView>
    );
  }
}

export default Scan;

somehow i have converted in my branch but its not working as before I have put as my best to convert the code but lots of errors i am getting pls help me out.

HTML5 datalist: Show all options in dropdown when arrow clicked

There are a few solutions out there to display all the options in a datalist dropdown when a value is set and the down arrow is clicked. But none of them dealt with the case when a placeholder was already set initially.

I have therefore adapted a solution so that the initial placeholder is restored.

How it works:

  • Down arrow clicked: Set a placeholder with the input value and clear the input value
  • On mouseenter event: Save the original/initial placeholder value
  • On mouseleave event: Restore the input value and restore the initial
    placeholder, if the input value is blank.

My question is, if you see any flaws or unhandled cases in this code.

https://jsfiddle.net/Smolo/1y9mne2o/

function dlRestoreValue(i) {

    let t = $('#' + i);
    if (t.val() === '') {

        if (t.attr('org-placeholder') !== t.attr('placeholder')) {
            t.val(t.attr('placeholder'));
        }

        t.attr('placeholder', '');
        if (t.val() === '') {
            t.attr('placeholder', t.attr('org-placeholder'));
        }
      
    }

}

function dlShowAllOnArrowClick(i) {

    $('#' + i)
        .on('click', function(e) {

            let t = $(this);
            if ((t.width() - (e.clientX - t.offset().left)) < 14) {
                if (t.val() !== "") {
                    t.attr('placeholder', t.val());
                    t.val('');
                }
            } else {
                dlRestoreValue(i)
            }
        })

    .on('mouseleave', function() {
        dlRestoreValue(this.id);
    })


    .on('mouseenter', function() {
        if (!$(this).is("[org-placeholder]")) $(this).attr('org-placeholder', $(this).attr('placeholder'));
    })

}


dlShowAllOnArrowClick('favcolors');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Favorite color:
  <input type="text" id="favcolors" list="colors" placeholder="Pick a color">
  <datalist id="colors">
   <option value="Blue">
   <option value="Brown">
   <option value="Cyan">
   <option value="Green">
   <option value="Orange">
   <option value="Pink">
   <option value="Purple">
   <option value="Red">
   <option value="Yellow">
  </datalist>

Updating date in Javascript

I’m trying to create a simple “availability schedular” from scratch using Python, Javascript and a bit of Bootstrap (and eventually Django). I know a bit of Python but am new to Javascript.

Project is on fiddle here:
https://jsfiddle.net/surista/a85y7x31/21/

I am trying to show just one week at a time (Sun – Sat), with three header rows: First header is current month and year based on the Sunday of week currently being shown, second row the days of the week, third row is the dates. Below that I have Previous and Next buttons to move forward / backward a week.

When the page is launched, it defaults to the initial week starting from the most recent Sunday, the table and dates are created dynamically. I have this working fine.

today = new Date();

This is used as the basis for initially populating the table with the current week. Right nowe, if you launch the page, today is ‘Mon Dec 27 2021’, and the table shows the current week from the most recent Sunday – ie, Sun Dec 26 2021.

I have three functions that move the week back and forth:

function addDays(dateObj, numDays) {
  dateObj.setDate(today.getDate() + numDays);
  return dateObj;
}

function nextWeek() {
  today = addDays(new Date(), 7);
  showWeek(today);
}

function previousWeek() {
  today = addDays(new Date(), -7);
  showWeek(today);
}

Clicking ‘Previous’ a few times updates fine until Sun Nov 28, and then the month flipping back seems to break it. Ditto going forward with Next. If I go Next, then Previous, I should end up where I started, instead it goes to Sun Jan 2 (as it should) then Sun 21 Nov.

Basically it seems to work perfectly until the month changes. I have a function that I use to pull the days of the month:

function daysMonth(xMonth, xYear) {
  daysInCurrentMonth = 32 - new Date(xYear, xMonth, 32).getDate();
  return daysInCurrentMonth;
}

I’ve tested this and it seems to be working exactly as expected, and I’m always passing in the current base date, so not sure why this wouldn’t be working.

Any thoughts on what I should be looking at?

Error in putting ImageView component within View component

When I’m putting ImageView component within View component, I am getting the error: Error: Text strings must be rendered within a component. I don’t understand what is wrong over here. Below is the code snippet:

import React from 'react';
import { View, Image, ScrollView, TouchableOpacity, Modal, Text } from 'react-native';
import styles from './cameraStyles';
import ImageView from "react-native-image-viewing";

export default ({captures=[], lflagImage=false}) => {
    const [flagImage, setflagImage] = React.useState(lflagImage);
    return (
        <ScrollView horizontal={true} style={[styles.bottomToolbar, styles.galleryContainer]}>
            {captures.map(({ uri }) => (
                <View style={styles.galleryImageContainer} key={uri}>
                    <TouchableOpacity onPress={()=> {setflagImage(prevData => !prevData)}}>
                        <Image source={{ uri }} style={styles.galleryImage}/>                       
                    </TouchableOpacity>
                    <ImageView
                        images={captures}
                        imageIndex={0}
                        visible={flagImage}
                        onRequestClose={() => setflagImage(prevData => !prevData)}
                    />
                </View>
            ))}
        </ScrollView>
    )
}

Phaser 3 game shirt on the top, pants at the back

so I am creating a game using Phaser 3, with a little treat at the end which is to allow people to customize the characters by selecting the outfits that they want. I am able to finish up the customizing, but now I was wondering if it is possible to have the shirt to always be at the top layer, and the pants to be behind the shirt. You are able to select the shirt or pants first, but whatever is selected second would overlap the first like the image below

enter image description here

I would like for it to be the shirt to always be on top, and the pants to always be below, regardless of whether you select the shirt first or the pants first, like the image below

enter image description here

The code below is the code for when the character has any piece of clothing on. Do help me out if possible I would really appreciate it.

tabs.getElement("panel").on(
      "cell.down",
      function (cellContainer, cellIndex, pointer) {
      console.log(playercoin);
        const name = filter.toLowerCase() + "Image" + cellIndex;
        localStorage.setItem("wa", name);
        let itemToRemove;
        for (let i = 0; i < playerContainer.length; i++) {
          const containerItem = playerContainer.list[i];
          if (containerItem.data.get("name") === filter.toLowerCase()) {
            itemToRemove = containerItem;
            itemToRemove.cost = containerItem.data.get("cost");
            break;
          }
        }
        const costUrl = cellContainer.data.get("costUrl");
        const newCost = GetCostFromUrl(costUrl);

React: TextField onchange

I have a list of data that lists on the collapse, I just want to display in my collapse what i put on my Textfield

const onChangeLocation = (locations) =>{
    console.log(locations)
  }

   <TextField
      size="small"
      fullWidth
      onChange={onChangeLocation}
      variant="standard"
      placeholder="Search Locations"
      onFocus={openSearch}
      value={searchParameter}
      }}
    />

  <Collapse in={viewLocationList} sx={{ my: '2px' }}>
    <Box className="rounded-scrollbar widget-result-container">
      {locations.map((location, index) => (
        <LocationWidgetItem
          key={index}
          location={location}
          onClickLocation={setActiveLocation}
        />
      ))}
    </Box>
  </Collapse>