Why does ReactJS component, which is a function, have to be put in inside tags at the ReactDom.render() method?

I am very very new to ReactJS and JavaScript in general, so I am having difficulty trying to make sense of the syntax.

I have the following very basic component:

import React from 'react'
import ReactDom from 'react-dom'

function Greetings()
{
  return <h1>Hello World</h1>
}

which I am trying to render using the below line:

ReactDom.render(<Greetings/>, document.getElementById('root'))

Now I am having difficulty trying to make sense of the syntax:

ReactDom.render(<Greetings/>, document.getElementById('root')),
where Greetings() is a function.

So what does enclosing it in tags mean ?

Pass state back to parent AND pass other props from parent to child in React

I know how to pass the state from child to parent. And I know how to pass props from parent to child.

However, the obvious way for doing both at the same time doesn’t seem to work as I expected. Please see an example below.

import React, { useState } from "react";

const Child = (props, { other }) => {
  // This is what I'd like to achieve but it ignores the {other} prop and doesn't received it from parent

  // const Child = ({ other }) => { // Works, but the sending of props from child to parent stops working
  // const Child = (props) => { // Works too but obviously the 'other' prop is not passed anymore
  return (
    <>
      Child
      <button onClick={() => props.setValue("New stuff")}>Click!</button>
      <p>{other}</p>
    </>
  );
};

const Parent = () => {
  const [value, setValue] = useState("Default value");

  return (
    <>
      Parent <Child setValue={setValue} other={"Something else"} />
      <p>{value}</p>
    </>
  );
};

export default Parent;

I tried passing both as {props, other}, (props, other), ({props, {other}}) but nothing worked.

Here is a link to Codesandbox.

Changing how an object/function is represented in a console.log statement [duplicate]

I am trying to customize how an instance is printed in a console.log statement by default:

function Vehicle(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.speed = 0;
    this.engineOn = false;
}

Vehicle.prototype.valueOf = function() {
    return 'print this';
}

let v = new Vehicle(1,2,3);
console.log(v);

It seems there is a valueOf and a toString function, but neither of those seem to change the value. How would I properly change the default format when it’s cast to a string in the console.log statement?

JavaScript usage of ‘const’ inside for-loop body ? (I am confused) [duplicate]

How can the same ‘const’ be initialized multiple times in a for-loop? I thought ‘const’ can only be initialized once. I’m a beginning developer.

Does the const element get deleted each iteration and have to be redeclared?
After a for-loop iteration loops each time, are all variables that were in its body deleted/lost?

const constDiv = document.createElement('div');

for (let i = 1; i <= 10; i++) {
    const element = document.createElement('p');
    element.textContent = 'This is paragraph number ' + i;

    element.addEventListener('click', function respondClick(event) {
        console.log('A <p> was clicked');
    });

    constDiv.appendChild(element);
}

document.body.appendChild(constDiv);

d3.js Uncaught (in promise) TypeError: d3.forceSimulation is not a function

I am new to d3.js and I am trying to learn by changing/looking at chunks of code.

I am running into the following issue: I get a Uncaught (in promise) TypeError: d3.forceSimulation is not a function

This is the line where I am getting the error:

const simulation = d3.forceSimulation(nodes)
    // .force('charge', d3.forceManyBody().strength(5))
    .force('x', d3.forceX().x(function(d) {
        return xCenter[d.category]
    }))
    .force('y', d3.forceY().y(0))
    .force('collision', d3.forceCollide().radius(d => 1.1*d.r*Math.sqrt(2)))
  //.force('collision', collide)
    .on('tick', ticked)

I have the following d3.js version loading in my html: <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

If I load <script src="./../d3.v6.js"></script> nothing will render. What might be the problem here?

The image drawn on the canvas with safari is not displayed

I am making a program that reads a video and displays one second later as an image. The image is displayed correctly on Mac, but the image is not displayed on Safari on iphone. There are no particular errors.

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
</head>
<body>
<input id="input" type="file" accept="video/*">
    <video hidden id="video" width="780" height="1280" controls="false"></video>
    <svg hidden id="svg" width="100%" height="100%" viewBox="0 0 720 1080">
        <image id="image" width="320" height="300" href="" />
    </svg>
 <script>
        const video = document.querySelector('video');
        input.onchange = event => {
            let reader = new FileReader();
            reader.readAsDataURL(input.files[0]);
            reader.onload = function () {
            video.src = reader.result
            video.load();
        };
        }
        video.addEventListener('seeked', function () {
           document.getElementById("image").setAttribute('href', toDataURL(video))
           

        });
        video.addEventListener('loadeddata', function () {
            video.currentTime = 1;
        })

        function toDataURL(target, type) {
            const canvas = document.createElement('canvas')
            canvas.width = target.width
            canvas.height = target.height
            canvas.getContext('2d').drawImage(target, 0, 0, target.width, target.height)
            canvas.getContext("webkit-3d", { preserveDrawingBuffer: true });
            canvas.type = "hidden";
            return canvas.toDataURL()
        }
</body>

What’s wrong?

Creating a ‘const const’ object in javascript

In javascript, if I create a const array, I can still modify the object the variable points to:

// The const declaration creates a read-only reference to a value. 
// It does not mean the value it holds is immutableβ€”just that the variable identifier cannot be reassigned.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
const x = [1,2,3];
x.push(4);
console.log(x);
x=55 // But this is illegal and will error
console.log(x);

Is there a way to make the elements in an array immutable as well? Similar to something like const int* const x; in C?

How to make image follow mouse cursor

I have set up this code where the image follows the mouse cursor. However, for some reason it is not working properly on the second container.

https://codepen.io/stefanomonteiro/pen/jOarjgX

PS: Irrelevant: Stackoerflow first force me to pste the code instead of only codepen link. Now it says it is mostly text. This companies should relly less on bots. It gets annoying sometines πŸ™‚

const items = document.querySelectorAll('.container')

items.forEach((el) => {
  const image = el.querySelector('img')
  
  el.addEventListener('mouseenter', (e) => {
    gsap.to(image, { autoAlpha: 1 })
  })
  
   el.addEventListener('mouseleave', (e) => {
    gsap.to(image, { autoAlpha: 0 })
  })
  
  el.addEventListener('mousemove', (e) => {
    gsap.set(image, { x: e.pageX, y: e.pageY })
  })
})
.container {
  display:inline-block;
  background:#ff0000;
  width:100%;
  height:200px;
}
.container:nth-child(2){
  background: #00ff00;
}

.container img.swipeimage {
  position: absolute;
  width: 200px;
  height: 200px;
  object-fit: cover;
  transform: translateX(-50%) translateY(-50%);
  z-index: 9;
  opacity: 0;
  visibily: hidden;
  pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<div class="container">
  <img class="swipeimage" src="https://source.unsplash.com/random">
  
  <div class="text">
    <h1>One</h1>
  </div>
  
</div>
<div class="container">
  <img class="swipeimage" src="https://source.unsplash.com/random">
  
  <div class="text">
    <h1>Two</h1>
  </div>
  
</div>

‘Blynk’ was not declared in this scope

I am doing an arduino project with my Esp32 and I got the code off an instructable. And 9/10 times the code never works on instructables and the person isn’t responding to my comments. Anyways, it is supposed to be a IOT garden that uses the sensor DHT 22 and a capacitive moisture sensor. It’s suppose to run through the Blynk app but the code is all messed up. The initial code had a lot of unnecessary libraries and didn’t even finish. It would just say”include#…” and have nothing else. After I deleted the unnecessary bits I got the error ‘Blynk’ was not declared in this scope. I know this is a common problem but if you also see any other errors in my code I would appreciate this very much. Thank you ahead of time for the help.

#define BLYNK_PRINT Serial
#include "DHT.h"

//DHT sensor information 
#define DHTTYPE DHT22  // DHT 22  (AM2302), AM2321
#define DHTPIN 27 // Digital pin connected to the DHT sensor
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.

//define input pins and outputs
int soil_sensor = 34; //define analog input pin number connected to moisture sensor

int output_value ;//define as output
int moisturelevel;//define as output

int notified = 0; //define notifed as 0
int timedelay= 60000L; //set timer to run get data once every minute or 60,000 miliseconds

//set minimum values for plant
int min_moisture =20;
int min_temperature =75;
int min_humidity =60;

// You should get Auth Token in the Blynk App.
char auth[] = "Auth_Token_Here";

// Your WiFi credentials.
char ssid[] = "Wifi_Network_Here";
char pass[] = "Wifi_Password_Here";


// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.

void Sensors () //main function to read sensors and push to blynk 
{
 output_value = analogRead(soil_sensor);// Read analog signal from soil_sensor and define as output_value
 //Map output_vlaue from min,max values to 100,0 and constrain between 0,100
 //Use sample code and serial monitor to find min and max values for individual sensor and soil type for better calibration
 moisturelevel = constrain ( map(output_value, 1000, 4095, 100, 0), 0, 100);
 float h = dht.readHumidity(); // Read humidity 
 float t = dht.readTemperature(); // Read temperature as Celsius (the default)
 float f = dht.readTemperature(true); // Read temperature as Fahrenheit (isFahrenheit = true) 
 // Compute heat index in Fahrenheit (the default)
 float hif = dht.computeHeatIndex(f, h);
 // Check if any reads failed and exit early (to try again).
 if (isnan(h) || isnan(t) || isnan(f)) {
 Serial.println(F("Failed to read from DHT sensor!"));
  return;
 }
 //This connects vales to virtual pins defined in the widgets in the Blynk app
  Blynk.virtualWrite(V5, moisturelevel );// Send moisture level to virtual pin 5
  Blynk.virtualWrite(V6,f);// Send temperature to virtual pin 6
  Blynk.virtualWrite(V7,h);// Send humidity to virtual pin 7 
  Blynk.virtualWrite(V8,hif);// Send heat index to virtual pin 8

 if (notified==0)
{
 if (moisturelevel <= min_moisture) // If moisturelevel is equal to or below min value
 {
  Blynk.email("Email_Here", "Plant Monitor", "Water Plant!"); // Send email to water plant 
 }
 delay (15000); // Blynk emails must be 15 seconds apart. Delay 15000 millisecons 
 if (f <= min_temperature) // If temperature is equal to or below min value 
 {
  Blynk.email("Email_Here", "Plant Monitor", "Temperature Low!"); // Send email that temperature is low

 }
 delay (15000); // Blynk emails must be 15 seconds apart. Delay 15000 millisecons 
 if (h <= min_humidity) // If humidity is equal to or below min value 
 {
  Blynk.email("Emial_Here", "Plant Monitor", "Humidity Low!"); // Send email that humidity is low
 }
notified = 1;
timer.setTimeout(timedelay *5, resetNotified); // multipy timedelay by number of minutes wanted between repeat warning emails 
}
}   

void resetNotified() //function called to reset email frequency  
{
  notified = 0;
}

void setup()
int Blynk.begin;
{
  Serial.begin(9600); // Debug console
  Blynk.begin(auth, ssid, pass); // connect to blynk 
  timer.setInterval(timedelay, Sensors); // Setup a function to be called every minute or what timedelay is set to
  dht.begin(); //run DHT sensor
}

//Void loop should only contain blynk.run and timer
void loop()
int Blynk.run;
{
  Blynk.run(); // Run blynk 
  timer.run(); // Initiates BlynkTimer
}

Delete Command After Execute discord.js

How do i make my command delete from chat after executing in this code:

    const Discord = require("discord.js");

module.exports.run = async (client, message, args) => {
    if (message.author.id != process.env.OWNERID)
        return message.channel.send("Only my developer can use this command...");
    const msg = args.slice(0).join(" ");
    if (!msg) return message.reply("Send something!");
    message.channel.send(msg);
};

module.exports.help = {
    name: "send-message",
    description: "N/A",
    usage: "d!send-message [Message]",
    accessableby: "Bot Owners",
    aliases: []
};

like if i were to do ” d!send-message discord.js help

how would i make “d!send-message discord.js help” delete from discord chat by the bot after executed?

unable to read the POST parameter values posted from html in php

Its a simple javascript-php scenario works in all browsers except in Firefox.

<script type=”text/javascript”>
loadPage(“test.php”,”Home.php”,”NONE”,”NONE”);
function loadPage(actionClass,screenInfo,parameters,applyMsg) {
  var form = document.createElement(‘Form’);
  form.setAttribute(‘method’,’POST’);
  actionClass = screenInfo ;
  form.setAttribute(‘action’,actionClass);
  screenInfoElement = document.createElement(“INPUT”);
  screenInfoElement.setAttribute(“type”,”hidden”);
  screenInfoElement.setAttribute(“id”,”LOAD_PAGE”);
  screenInfoElement.setAttribute(“name”,”LOAD_PAGE”);
  screenInfoElement.setAttribute(“value”,screenInfo);
  form.appendChild(screenInfoElement);
  parametersInfoElement = document.createElement(“INPUT”);
  parametersInfoElement.setAttribute(“type”,”hidden”);
  parametersInfoElement.setAttribute(“id”,”parameters”);
  parametersInfoElement.setAttribute(“name”,”parameters”);
  parametersInfoElement.setAttribute(“value”,parameters);
  form.appendChild(parametersInfoElement);
  applyMsgElement = document.createElement(“INPUT”);
  applyMsgElement.setAttribute(“type”,”hidden”);
  applyMsgElement.setAttribute(“id”,”APPLY_MSG”);
  applyMsgElement.setAttribute(“name”,”APPLY_MSG”);
  applyMsgElement.setAttribute(“value”,applyMsg);
  form.appendChild(applyMsgElement);
  alert(“LOAD Page Called from Pagemap.cs 2″ +screenInfo +”,actionClass : “+actionClass+”, ApplyMSG : “+ applyMsg +”, parameters : ” +parameters);
  document.body.appendChild(form);
  form.submit();
}
</script>
I could the see values being populated in the Alert box.

Now the handler in php, this method is in test.php
<?php
…..
$fileAccessArray = array(“allow”,”deny”,”val3″,”val4″);
isFileAccessValid($fileAccessArray);
…..
function isFileAccessValid($fileAccessArray)
{
// writeToLog(“******** FroM SessionManagementUtils.php –> isFileAccessValid() **“);
$page = false;
$pg = “NO PAGE SELECTED”;
echo nl2br(“n POST ARRAY From SessMgmt Page “);

writeToLog(“ FroM SessionManagementUtils.php –> $pg = **********”. $pg.”, POST “.implode(‘,’, $_POST) .”, GET “.implode(‘,’, $_GET) );
  if(isset($_POST[‘LOAD_PAGE’]) ) {
  if (in_array( $_POST[‘LOAD_PAGE’], $fileAccessArray)){
    $page = true;
    $pg =$_POST[‘LOAD_PAGE’];
   }
  } else if(isset($_GET[‘LOAD_PAGE’]) ) {
   if (in_array( $_GET[‘LOAD_PAGE’], $fileAccessArray)){
    $page = true;
    $pg =$_GET[‘LOAD_PAGE’];
   } else {
    killBackEndSession();
    destroyCurrentSession();
    $url =”login.php” ;
    header(“Location: $url?error=invalidFileRequested”);
   }
 }
return $page ;
}
?>
Content printed in the log file

[04-Feb-xxxxxxx] ******** FroM SessionManagementUtils.php –> $pg = **********NO PAGE SELECTED, POST , GET
[04-Feb-xxxxxxx]

Logfile shows there is no filename $pg = **********NO PAGE SELECTED,

However when called elsewhere it prints the values properly.

[04-Feb-xxxxxxx] ******** FroM SessionManagementUtils.php –> $pg = **********NO PAGE SELECTED, POST test.phpNONENONE, GET

This issue is also only in fire fox.

Any help is much appreciated.

To make a lightweight responsive design is it convenient to add the necessary html with javascript or hide it with css?

I want to make the best decision and I would like to know your comments, although the question is probably poorly qualified.

I observe that the popular sites, for the most part, adapt perfectly to changing the width of the screen by modifying it from the inspector for example, instead amazon seems not to do that but to detect if a mobile device or a computer is used and thus shows the content.

In my case, I have a layout that uses javascript to inject or remove html based on width. For example in the header search engine that displays recommendations in one window or another, and the dropdown menus also use a slightly different html for the content. Also, I use php to detect if it is a mobile and thus show a design with less content.

This doesn’t achieve a perfect responsive layout if it adjusts live, but it does display what I want based on the size when the page loads.
As far as performance is concerned, placing the elements in order with javascript in the footer loads fast but I’m not sure if this way of designing is appropriate since it’s my first design.

My intention is to save as much code as possible and make the site fast.

How to get order number after submitting form via ajax?

The order is created after the form is submitted.

 add_action( 'wp_footer', 'mycustom_wp_footer' );
function mycustom_wp_footer() {
?>
     <script>
                         
document.addEventListener( 'wpcf7submit', function( event ) {
    var inputs = event.detail.inputs;
    console.log(inputs);
}, false );
           </script>   

       <?php  }

I need to get the order number immediately after it is created from the form

add_action('wp_ajax_hello', 'say_hello1');
add_action('wp_ajax_nopriv_hello', 'say_hello1');

function say_hello1() {
    if (empty ( $_POST['order_id'])) {
    $order_id = absint( get_query_var('view-order') );
    $testart = $order_id;
    } else {
        $testart = ( $_POST['order_id']);
    }

    
    echo "ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ°, $testart!";
    wp_die();
}

I’m trying to get the order number when clicking on the submit form so that I can tell it to the customer. I can’t do anything.

add_action( 'wp_footer', 'my_action_javascript25', 99 );

function my_action_javascript25() {
    ?>
    <script>
    document.addEventListener( 'wpcf7submit', function( event ) {
        var datax = {
            action: 'hello',
            order_id: 'testpage'
        };
        jQuery.post( ajaxurl, datax, function( response ){
            alert( 'ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½ΠΎ с сСрвСра: ' + response );
        } );
    } );
    </script>
    <?php
}

How to trigger a Jquery Id from a yml url navigation in jekyll

I using using Jekyll and I already implemented a button that when clicked brings up a issue collector form from Jira. I am using the custom trigger function to implement this. The only problem I am having is that I am using jekyll to implement this. I’ve already got it working, but instead of the user clicking on the button execute I have a drop down menu that is implemented in jekyll. So, when the user clicks on the drop down and selects an option I would like for the form to get executed from there. Jira has this built Issue Collector that allows you to create custom field options and then it generates the html and javascript code for you. You then will need to place this code in your own website. There is an option that will allow you to pass in this jira form within the rest api, but this option doesn’t work when customizing it. So, pasting the generating code was the only option.

Below is the generated html code that I used for my github website.

<head>
    <!-- We pasted the generated code from the Issue Collector here, after choosing a custom trigger -->

    <!-- This is the script for the issue collector feedback form -->

    <script type="text/javascript"
        src="https://google.com/s/2345234523452345234523452345234/2342342/1qywti/234234234234/_/download/contextbatch/js/com.atlassian.google.collector.plugin.jira-issue-collector-plugin:issuecollector/batch.js?locale=en-US&collectorId=2323423"></script>

    <script type="text/javascript">window.ATL_JQ_PAGE_PROPS = {
            "triggerFunction": function (showCollectorDialog) {
                //Requires that jQuery is available! 
                jQuery("#feedback-button").click(function (e) {
                    e.preventDefault();
                    showCollectorDialog();
                });
            }
        };</script>

</head>

<body>

    <h2>JIRA Issue Collector Demo</h2>
    <a href="" id="feedback-button" class='btn btn-primary btn-large'>Report feedback</a>

</body>

<script src="../assets/js/IssueCollector.js"></script>

Below is the javascript code

// Requires jQuery!
jQuery.ajax({
    url: "https://google.com/s/2352345235234523452345-T/bf23452345/4qywti/2345234523455/_/download/contextbatch/js/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector-embededjs/batch.js?locale=en-US&collectorId=5717c9f7",
    type: "get",
    cache: true,
    dataType: "script"
});

 window.ATL_JQ_PAGE_PROPS =  {
    "triggerFunction": function(showCollectorDialog) {
        //Requires that jQuery is available! 
        jQuery("#feedback-button").click(function(e) {
            e.preventDefault();
            showCollectorDialog();
        });
    }};

I have a navigation.yml file that is used to execute each links when the user presses it from the drop down. Below I specified the url: /IssueCollector that goes to a new page from the markdown I specified at the very bottom. Everything works fine I just don’t want it going to a new page. I would like instead for the user to click the dropdown link and the form pops up then. Is there a way I could pass in the jquery id into the navigation.yml url where its specified below.
For example: The url below: /IssueCollector is passed, which will read from the permalink to the markdown page that displays the github. Is it possible to get the jquery id – #feedback-button passed into this url for it to read for the form to pop up.

 - title: "Contacts"
    sublinks:
      - title: "Request Help"
        url: "/IssueCollector"
      - title: "Provide Feedback"
        url: "https://google.com.com/rest/collectors/1.0/template/form/1935f94b?os_authType=none#"
      - title: "Mattermost"
        url: "https://mattermost.google.com/ng/channels/teamsptsstssd-lace"

Below is the jekyll code for creating the drop down.

{% if link.sublinks %}
              <li class="dropdown {{ class }}">
                <a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ link.title }}<i class="fa fa-caret-down fa-sm" aria-hidden="true"></i><span class="caret"></span></a>
                <ul class="dropdown-content" style="position: absolute; min-width: 250px">
                    {% for sublink in link.sublinks %}
                        <li>
                            <a href="{{ sublink.url }}">{{ sublink.title }}</a>
                        </li>
                    {% endfor %}
                </ul>
            </li>
              {% else %}

Below is the markdown code for passing in the html

title: Request Help 
permalink: /IssueCollector/
---

{% include /devops/IssueCollector.html %}