Passing data from a child component to a parent component (React)

I have a child component that has some states which change in value when you check or un-check some boxes; I want to be able to pass those state values to the parent component. I’ve tried a few things on the internet but nothing seem to work.

I’ve tried to (Parent Component File):

const ParentComponent = () => {

     const [ data, setData ] = useState();

     const childToParent = (childData) => {
          setData(childData);
     };

     return(
          <Child childToParent={childToParent} />
     );
}

and on the Child Component:

const ChildComponent = ({ childToParent }) => {

     const [ childData, setChildData ] = useState(false);

     const handleChange = () => {
          setChildData(!childData);
          childToParent(childData);
     };

     return(
          <div>
               <Checkbox value={childData} callback{() => handleChange()} />
          </div>
     );
}

Basically the problem is I dont get how to move data from a child component to a parent component.

How to freeze scrolling on a certain frame in Javascript or React.js

I have a website when I scroll to a certain position I want to freeze the scrolling functionality but be able to raise the other object when I am scrolling.

I did not find any useful articles on the internet, maybe someone knows how I can do it.

To sum up,

I have multiple sections on my website, when I scroll to section 3, I want to disable scrolling but be able to raise the block which is located in this section 3 – I want to create a parallax effect where we continue scrolling functionality once one block is raised up.

I want to freeze scrolling but be able to listen to the mouse scroll event.

I don’t need code, just tell me how I can do it. Thanks

How nike detect Puppeteer?

When I want to connect with a browser launched from puppeteer, POST requests from Nike is permanently blocked.
Yet I used puppeteer-extra-plugin-stealth.
I don’t understand how nike manages to detect Puppeteer.

My code :

const puppeteer = require('puppeteer-extra');
const pluginStealth = require("puppeteer-extra-plugin-stealth");

puppeteer.use(pluginStealth())

puppeteer.launch({
    headless: false
}).then(async browser => {
    const page = await browser.newPage()
    await page.goto('https://www.nike.com')
})

When i want to log in :
output

Struggling with this js Codewars challenge

I am learning js and struggling with a problem I encountered on Codewars.

I need to calculate how many numbers containing only binary digits exist between 1 and a random number n. For example, if n is 20, there are 3 such numbers: 1, 10, 11;

I have written a solution that works on codepen but Codewars is telling me it is too inefficient to be accepted. I can’t think of anything else I can do to optimize it. Thank you in advance for your help!

function incompleteVirus(n) {
  let countInMemory = 0;
  let isBinary = true;

  // Loop through all numbers below and including n
  for (let i = 1; i <= n; i++) { 

    let strCurrNum = String(i); 

    // Iterate through all digits in the current number
    for (const digit of strCurrNum) {
  
      let numDigit = Number(digit);
 
      // Check if each digit is binary; if not, exit loop
      if (numDigit > 1) {
        isBinary = false;
        break;
      } else {
        isBinary = true;
      }
    }

    // Update memory count
    if (isBinary) {
      countInMemory += 1;
    }
  } 
  return countInMemory
}

Markers not showing on Google Map

My custom markers aren’t coming up on a google map on my WordPress site. I’ve reviewed the code for bugs and I’ve seen the following error in the console: (index):573 Uncaught ReferenceError: myMarkers is not defined at initialize however I have another site with nearly the same exact code that is working fine and so I can’t figure out why myMarkers is not defined. I’ve tried rearranging the code to no avail. Has anyone seen this before? Thanks!

Map is at the bottom of the page here: https://excelsportspt.com/

Here is the code:

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBtKFXFKTieXTdke5jGk_KxZE6FYEADYxg"></script>
    <script type="text/javascript">// <![CDATA[
        jQuery(document).ready(function() {
            <?php if (have_rows('location_map', 'options')): ?>
                //set up markers
                myMarkers = {"markers": [
                    <?php while (have_rows('location_map', 'options')): the_row();
                        $loclatitude = get_sub_field('address_latitude', 'options');
                        $loclongitude = get_sub_field('address_longitude', 'options');
                        $locname = get_sub_field('address_name', 'options');
                        $locadd = get_sub_field('address', 'options');
                        $locmap = get_sub_field('loc_map_url');
                    ?>
                        {
                            'latitude': '<?= $loclatitude; ?>',
                            'longitude': '<?= $loclongitude; ?>',
                            'icon': '<?= esc_url(get_template_directory_uri()); ?>/images/map-pin.png',
                            'balloon_text': '<a target="_blank" href="<?= $locmap; ?>"><?= $locname; ?></a>'
                        },
                    <?php endwhile; ?>
                ]}
            <?php endif; ?>
            map = '';
            function initialize() {
                var myOptions = {
                    center: new google.maps.LatLng(38.7234409, -90.6383197),
                    zoom: 10,
                };
                map = new google.maps.Map(document.getElementById('map1'), myOptions);
                setMarkers(map,myMarkers.markers);
            }
           
            function setMarkers(map,markers) {
                var marker, i;
                for (i = 0; i < markers.length; i++) {
                    var lat = markers[i].latitude;
                    var long = markers[i].longitude;
                    var content =  markers[i].balloon_text;
                    var icon =  markers[i].icon;
                    latlngset = new google.maps.LatLng(lat, long);
                    var marker = new google.maps.Marker({
                        map: map,
                        title: content,
                        position: latlngset,
                        icon: icon
                    });
                    var infowindow = new google.maps.InfoWindow()
                    google.maps.event.addListener(marker, 'click', (function  (marker,content,infowindow) {
                        return function() {
                            infowindow.setContent(content);
                            infowindow.open(map,marker);
                        };
                    })(marker,content,infowindow));
                }
            }
           
            google.maps.event.addDomListener(window, 'load', initialize);
            jQuery(document).on('click', '.map-open', function(event) {
                event.preventDefault();
                map.setCenter(
                    new google.maps.LatLng(jQuery(this).data('lat'),  jQuery(this).data('long'))
                );
            });
        });
    </script>
       
    <div class="location-map" id="map1"></div>

Apollo Client GraphQL Unit Testing return Error: TypeError: (0 , _reactHooks.useQuery) is not a function

I was trying to write unit test with react component from Apollo Client Unit Testing, but I got an error when mocking call to the GraphQL endpoint to some hook functions.

My unit test implement:

import React from 'react';
import MockedProvider from '@apollo/react-testing';
import renderer from 'react-test-renderer';
import { GET_CHARACTER_DETAILS } from '../../containerHooks/useCharacterDetails';
import { UseCharacterDetails } from '../../containerHooks/useCharacterDetails';

const mocks = [
  {
    request: {
      query: GET_CHARACTER_DETAILS,
      variables: {
        id: 1,
      },
    },
    result: {
      data: {
        character: {
          id: '1',
          name: 'Rick Sanchez',
          status: 'Alive',
          gender: 'Male',
        },
      },
    },
  },
];

it('renders without error', () => {
  renderer.create(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UseCharacterDetails id='1' />
    </MockedProvider>
  );
});

Here is my Test Component

import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';

export const GET_CHARACTER_DETAILS = gql`
  query CharacterDetails($id: ID!) {
    character(id: $id) {
      id
      name
      status
      species
      type
      gender
      origin {
        name
      }
      location {
        name
      }
      image
      episode {
        name
      }
      created
    }
  }
`;

export const UseCharacterDetails = ({ id }) => {
  const { loading, error, data } = useQuery(GET_CHARACTER_DETAILS, {
    variables: { id },
  });

  return {
    data,
    error,
    loading,
  };
};

When I run a test, it throws an error

TypeError: (0 , _reactHooks.useQuery) is not a function

Is there a way to communicate client to client in a static website

I want to make a game with room system, like kahoot or stop. Using a static website (github pages):

My plain is to have two links,

link 1 – sitename/host.github.io

link 2 – sitename.github.io

the host device will connect to the 1 link and the players to the 2. The clients (devices at the 2 link) should be able to send data to each other, for example, if client1 selects a button, client2 will be informed.

Ps. this site is for my math teacher, and not always all the devices will be connected to the same wifi, like if he is in a online class. or the school wifi is bad and they have to use mobile data(4g, 3g, etc.) so I dont think it is a good idea to use LAN.

JavaScript post request to PHP file – No content available because this request was redirected

Failed to load response data: No content available because this request was redirected

I have no idea what this response message means whatsoever. Maybe stack can help?

This is the most specific I can get. The context is that I made a website and made a javascript post request to the .php file then checked network and it responded with the error above

I do not have an example code because it is not necessary the .php file is blank.

My php file:

<?php ?>

Resize CSS Grid Layout

So I am attaching a sandbox to help with this question.
https://codesandbox.io/s/xenodochial-benz-2333fv?file=/src/ResizeColumns.tsx:185-196

I have 2 control Divs.
one for Rows,
one for Columns, and
a Central grid area.

I would like for the black bars in the control divs on the side and bottom to allow for adjusting the CSS grid.

  • Not sure how to allow for the black bars to move.
  • Grid layout on control divs should update with bar movement.
  • Central grid layout needs to update with bar movement.

Any help would be greatly appreciated even if its just more learning/research material.

html2canvas artifacts and inconstancy

Few things with html2canvas are not predictable:
Below is a screenshot of pdf map.

I am using html2canvas to take a screenshot of google map, and then putting it on pdf by using php.

  • sometimes html2canvas will display a grayish faded rectangular shape close to the center (in the image below the shape is to the right of DV-2 marker). Sometimes it is there, sometimes it it is not, inconsistent on all modern browsers.
  • Most of the times one or more markers will not have label displayed. In image below the blue marker to the right does not have marker.

On the map, before taking the screenshot, the gray shape is not there and all markers have label visible.

Any thoughts / suggestions why it is happening? Like I mentioned earlier, it is unpredictable, sometimes that shape does not show up and sometimes all marker labels are visible.

I notice that the markers without label are put on the map first (when I console.log()). It is happening in html2canvas not after. Below is the vue.js method which grabs the screenshot.

genAndSubmit() {
            let xCrop = (this.dimensions.vw - this.dimensions.pw) / 2
            this.form.processing = true;
            html2canvas(document.querySelector("#mapWrapper"),
                {
                    useCORS: true,
                    logging: true,
                    width: this.dimensions.pw,
                    x: xCrop,
                    // allowTaint: true,
                    // foreignObjectRendering: true,
                    // imageTimeout: 30000,
                    // scale: 2,
                })
                .then(canvas => {
                    this.form.image = canvas.toDataURL('image/png');
                    this.submit();
                });
        },

enter image description here

Tapestry 3.58: How to display a tooltip during mouseover on a select Option

I’m actually working on a form that include a list box with Select options.

In the tml file, the select box is build as followed:

<t:select t:id="selectPo" t:value="selectPo" model="poSelectModel" encoder="encoderPo" id="selectPo"/>

in the Java File, i have a setUpRender as the following

@Property
private SelectModel poSelectModel;

@Inject
SelectModelFactory selectModelFactory;

public void setupRender() {
    poSelectModel = selectModelFactory.create(listePo, "label"); 
}

on a mouseover event, Is ist possible to display a tooltip with entire value of label if this label is too long to be displayed in the list box?

Thanks.

How to detect device is mobile when the website is clicked through TikTok and instagram?

I am trying to detect that a device is mobile in order to render the screen differently. We have a 4 column grid layout on desktop and want to display only 1 or 2 columns if the device is mobile.

This is the existing code:

  window.addEventListener(
    "resize",
    function (event) {
      if (event.target.innerWidth > 700) {
        setColumns(4);
      } else if (
        event.target.innerWidth < 700 &&
        event.target.innerWidth > 600
      ) {
        setColumns(3);
      } else if (
        event.target.innerWidth < 600 &&
        event.target.innerWidth > 400
      ) {
        setColumns(2);
      } else {
        setColumns(1);
      }
    },
    true
  );

It seems that this logic is good enough to only show 2 columns when I am on my iPhone via my Chrome browser. However, when I try clicking on the link to our website through a TikTok profile, it seems that we still display 4 columns. Why is this different than opening it via my mobile Chrome browser and how would you recommend fixing this? Thanks!

Axios and Vue Js Get Request With Aws (Public, Read Permissions) [duplicate]

I’m rather stuck with getting images using Axios from AWS. I’m receiving an error that I’m unfamiliar with:

enter image description here

I have hosted the image here: https://do-not-delete-ct-images.s3.us-west-2.amazonaws.com/1024-2.png with the rules set to publicly available for read only.

And this is the code I’m using:

axios.get("https://do-not-delete-ct-images.s3.us-west-2.amazonaws.com/1024-2.png").then(response=>{
    console.log("get data: ", response.data);
}).catch(err =>{
    console.log("get data err: ", err);
})

Thanks in advance and apologies if this is an unwise mistake.

Migrate from GWT to JS frameworks

I have a JS library that is embedded into multiple other websites.
This library creates

  1. Widgets (like the usual chat widget seen on multiple apps). These widgets are primarily iFrames
  2. Also it monitors the application state to show certain messages to users on certain actions. This is primarily logic that listens
    to events on page, tracks all mutations etc.

This library is entirely coded in GWT. Facing problems in retaining and hiring FrontEnd developers to work in Java.
Thinking of moving to React for widgets and Typescript for logic.
Queries:

  1. Is React + Typescript a good choice ? I evaluated Vue, Svelte. Are there any other frameworks/libraries that can be considered ?
    [Note that this library sits on top of multiple websites built in variety of ways. Primary requirement is to avoid any kind of javascript namespace conflicts]

  2. For widgets where most of the logic is UI related, and which are restricted to iFrames, we are thinking of rewriting the code in React. Is there something else we can do ?

  3. For logic(where there is no UI related code) , is there a way I can directly convert all GWT code to human readable and maintainable Typescript at once ?

  4. Any other way to undertake this overall migration ?

I need help forwarding a javascript request to my php file to another website with the same headers and everything

I am trying to get the contents of https://thumbnails.roblox.com/v1/batch using a javascript request but obviously CORS is going to block it because the origin does not allow javascript requests. I need help forwarding the javascript request to https://thumbnails.roblox.com/v1/batch with the same headers and request and everything.