Rerendering child component when parent state changes in React

I’m still pretty new to React, so I’m sorry if this has a simple answer. I’m trying to make a bar at the top of the page re-render every time the URL changes (with React Router). After struggling with this for a while (please let me know if you have any thoughts on an easier solution!), I decided to update the state when a URL changes and pass this new state into a component. Here is a simplified version of the code:

    import React from 'react';
    import {
      AppBar, Toolbar, Typography
    } from '@material-ui/core';
    import './TopBar.css';

    class TopBar extends React.Component {
      constructor(props) {
        super(props);

        this.state = {
          url: props.url
        }

        this.parseURL = this.parseURL.bind(this);
      }
      
      

      static getDerivedStateFromProps(props, state) {
        if (state.url !== props.url) {
          return {
            url: props.url
          }
        }

        return null;
      }

      render() {
        return (
          <AppBar position="absolute">
            <Toolbar>
              <Typography variant="h5" color="inherit">
                {this.state.url}
              </Typography>
            </Toolbar>
          </AppBar>
        );
      }
    }
    
    export default TopBar;
import React from 'react';
import ReactDOM from 'react-dom';
import {
  HashRouter, Route, Switch
} from 'react-router-dom';
import {
  Grid, Typography, Paper
} from '@material-ui/core';
import './styles/main.css';

import TopBar from './components/topBar/TopBar';
import UserDetail from './components/userDetail/userDetail';
import UserPhotos from './components/userPhotos/userPhotos';

class PhotoShare extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      url: window.location.href
    }
  }

  render() {
    return (
      <HashRouter>
      <div>
      <Grid container spacing={8}>
        <Grid item xs={12}>
          <TopBar url={this.state.url} key={this.state} />
        </Grid>
        
        <Grid item sm={9}>
          <Paper className="cs142-main-grid-item">
            <Switch>
              <Route path="/users/:userId"
                render={ props => {
                  this.state.url = props.match.params.userId;
                  console.log(this.state.url);
                  return <UserDetail {...props}
                  key={props.match.params.userId} />;} }
              />
              <Route path="/photos/:userId"
                render={ props => {
                  this.state.url = props.match.params.userId;
                  console.log(this.state.url);
                  return <UserPhotos {...props}
                  key={props.match.params.userId} />;} }
              />
            </Switch>
          </Paper>
        </Grid>
      </Grid>
      </div>
      </HashRouter>
    );
  }
}


ReactDOM.render(
  <PhotoShare />,
  document.getElementById('photoshareapp'),
);

The console.log statements when I click a link show that the url state in the PhotoShare component is changing, but the TopBar component is not re-rendering when it changes. Is there any way to make sure it re-renders? Thanks for any help!

Can I define nested component without creating new file?

What I want:

Parent.vue

<template>
    <div>
        <span>{{foo}}</span>
        <Child/>
    </div>
</template>

<script setup>
import { ref, defineComponent } from 'vue';

let foo = ref('foo');

let Child = defineComponent({
    name: 'Child',
    template `<span>{{bar}}</span>`,
    setup() {
        let bar = ref('bar');

        return { bar };
    }
};
</script>

I wanted to make very small dedicated component for one page.

It looks pretty good. But it doesn’t work.

I don’t want to make a new file and use export default.

and also don’t want register it globally.

Is there no way to create component like this?

Get values of specific objects from group of arrays in JS

I have 2 select tags both are dynamic and option data is coming from data.json, like this:

<select>
<?php
     $str = file_get_contents('data.json');
        $b = json_decode($str);

        foreach ($b->{'sheet'} as $value) {
       ?>

<option><?php echo $value->{'category'} ?></option>
<?php }?>
</select>
<select>
 <option>*Subcategories*</option>
</select>

All I want is when my user selects any option from 1st Select, the Subcategories related from that specific value should come in the place of Subcategories, how can I do it?

This is how my data.json file looks like:

{ "sheet": [
        {
            "category": "something",
            "subcategory": "some value",
            "subcategory2": "some value 2"
        },
        {
            "category": "something 2",
            "subcategory": "some value",
            "subcategory2": "some value 2",
            "subcategory3": "some value 3"
        },
        {
            "category": "something 3",
            "subcategory": "some value",
            "subcategory2": "some value 2"
        } ] }

And I cannot change it, as my clients wants only this json.
So, what should I do in order get subcategories related what is choosed from 1st select from my json. You can give solution in PHP, Js or Jquery.

Firebase Auth with Google using signInWithPopup only works on mobile not on desktop

in creating a project with React and Im currently trying to create a login using Firebase with Google and signInWithPopup, but when I touch the button to trigger the popup, the popup shows but blank, but with the correct URL

PopUp Screen Image

When I do the same on mobile, its make the redirect and choose my account.
Also all the rest of the Firebase features works

This is the code for the signInWithPopUp

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
var provider = new GoogleAuthProvider();

export const signInWithGoogle = () => {
  return signInWithPopup(auth, provider);
}

And this is the code for the login page:

import React from 'react'
import { signInWithGoogle } from "../Firebase";

const Login = () => {

    function InitWithGoogle() {
        signInWithGoogle();
    }

    return (
           <button type="button" onClick={InitWithGoogle} className="login-with-google-btn" >Sign in with Google</button>

    )
}

export default Login

Also this is the errors I get on console:
Console error messages image

Thanks in advance!

JavaScript: Filter object, keeping unique properties

I have an object that I need to filter against and return a new object. The goal is to get all ids that contain “A” in val, BUT only include ids with a unique val.

Below is what I’m currently doing, but I wonder if there’s a more efficient way to do this. As can be seen when you run the code snippet, the new object should look like this:

{
  "id1": {
    "val": "AAA"
  },
  "id4": {
    "val": "ABC"
  }
}

const obj = {
  id1: {
    val: 'AAA',
  },
  id2: {
    val: 'BBB',
  },
  id3: {
    val: 'AAA',
  },
  id4: {
    val: 'ABC',
  },
};

// Filtered object
const obj2 = {};
let matched = '';

for (const key in obj) {
  if (matched.indexOf(obj[key].val) < 0 && obj[key].val.indexOf('A') > -1) {
    obj2[key] = obj[key];
    matched += obj[key].val + ' ';
  }
}

console.log(obj2);

Cypress error: > ev.element is not a function

When running a cypress test I am getting an error message that states the following:

The following error originated from your application code, not from Cypress.

ev.element is not a function

This is happening on a line of code where it is simply clicking an element

cy.get('#report_submit').click()

I styled focus state for my webpage. But even after I’m done clicking button/link, the focus stays, unless I click whitespaces. How do I make it go?

I’ve styled the focus state for my webpage to my liking. But now it stays on the buttons/links even when I’m done clicking them. I have to click the blank spaces to make it go away. I only want the focus state to be visible when we use TAB key for shifting focus, and(optional) when the buttons are clicked. How can I do that? Do I need to write some JavaScript for that? Basically I want the focus state to behave in a default way, the way it did before I styled it.

*:focus {
  outline: none;
  box-shadow: 0 0 0 0.5rem rgba(61, 112, 46, 0.5);
}

.cta *:focus {
  box-shadow: 0 0 0 0.5rem rgba(255, 255, 255, 0.5);
}

How do I set MessageEvent property, e.g lastEventId in WebSocket message

As mdn “WebSocket: message event” said onmessage = event => { } , the event is a MessageEvent, the most commonly used property is, of course, event.data, but there are other properties, e.g. lastEventId I would like to use, as mdn said “The lastEventId read-only property of the MessageEvent interface is a string representing a unique ID for the event.”

But on the other hand the send() method for websocket can only send string or ArrayBuffer or Blob, so it seems nowhere to set MessageEvent properties.

As matter of fact, when I print out the MessageEvent value, lastEventId is always an empty string, e.g. VM680:1 MessageEvent {isTrusted: true, data: 'xxx', origin: 'ws://localhost:3000', lastEventId: '', source: null, …}

So is it possible to set this property of MessageEvent (along with others) in websocket? If not who set those value for us?

BTW, the answer in Is there any ID for data chunks in WebSocket like lastEventId? mentioned a message in https://web.dev/eventsource-basics/#toc-introduction-differences

Server-Sent Events have a variety of features that WebSockets lack by
design such as automatic reconnection, event IDs, and the ability to
send arbitrary events.

But that document was published in 2010 while the mdn articles I mentioned said “Last modified Jun 3, 2022”

Unable to validate form using js

I am trying to validate a form by seeing if all the inputs are filled. So here when either email or password are empty, it should return an alert. But when I run this html file, it isn’t alerting me of that.

My code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script> 
        function validateform(){  
            var name=document.login.email.value;  
            var password=document.login.password.value;  
            
            if (name==null || name==""){  
            alert("Name can't be blank");  
            return false;  
            }else if(password.length<6){  
            alert("Password must be at least 6 characters long.");  
            return false;  
            }  
        }  
</script>  
<body>  
    <form name="login" onsubmit="return validateform()" method="post" action="/login_process">
        <label for="email">BCBS outlook email</label>
        <br>
        <input type="email" name="email" id="email" text="BCBS outlook email">
        <br>
        <label for="pass">Password</label>
        <br>
        <input type="password" name="pass" id="pass">
        <br>
        <input type="submit" value="submit">
    </form>
</body>
</html>

Thanks in advance.

Need form to redirect user if they select age below 18

I am working on a site with an html form, and the form requires the user to submit their age.

The user’s age will be used for various purposes through-out the website’s program.

However, if the user is under the age of 18, they are not eligible to participate in the program anyway.

Therefore… if the user selects ‘Under 18’ in the form, and then tries to click the ‘continue’ (submit) button, I need the form to automatically redirect the user to another URL.

I have tried several php, and a few javascript solutions, but so far, no dice.

And help or advice would be greatly appreciated.

I have included the form page which asks for the user’s age.

Form Page

<!DOCTYPE html>

<head>

<title>Form Page</title>

</head>

<body>

<form action="nextPage.php" method="POST">

Please select your age:<br><br>

<select id="userAge" name="userAge" class="ageField" required>
<option value="0" selected="selected" disabled="disabled">Age</option>
<option value="Under 18">Under 18</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
<option value="33">33</option>
<option value="34">34</option>
<option value="35">35</option>
<option value="36">36</option>
<option value="37">37</option>
<option value="38">38</option>
<option value="39">39</option>
<option value="40">40</option>
<option value="41">41</option>
<option value="42">42</option>
<option value="43">43</option>
<option value="44">44</option>
<option value="45">45</option>
<option value="46">46</option>
<option value="47">47</option>
<option value="48">48</option>
<option value="49">49</option>
<option value="50">50</option>
<option value="51">51</option>
<option value="52">52</option>
<option value="53">53</option>
<option value="54">54</option>
<option value="55">55</option>
<option value="56">56</option>
<option value="57">57</option>
<option value="58">58</option>
<option value="59">59</option>
<option value="60+">60+</option>
</select>

<br><br><br>


<input type="submit" class="continueButton" value="Continue">


</form>

</div>   

</body>

</html>

Vue – Using a list of objetc from data in a function on methods, to check if is equal with a input

So i am new in vue and JS in general, and i am trying to do a user and password check with framework vue.
In the “.js” i have a list object inside in data, what contain parameters like user and password.
Then i use this list in a function on methods, to check if the input is equal to one of the user in the list with a if.

the problem is, all the items on methods are undefined using the respective console log (but those items exist with the proper v-for in the html).

this is a example of the code.

const app=new Vue({
el:"#app",
data:{
    list:[
        {user:'cpalma',password:'123456'},
        {user:'cjara',password:'654321'}
    ],
    tryUser:'',
    tryPass:'', 
},
methods:{
    checkPass(){
        console.log(this.list.user);
        for(item in this.list){
            if(item.user == this.tryUser){
              // rest of code
        }
    }
}

Vue version is 2.5
“checkPass” is execute with a button.
tryUser and tryPass are get from the html with his respective v-model.

So if anyone can explain what is my error and how to fix it i will be in eternally grateful

Keep selected drop down menu option visible after page reload

I have an error message that only shows if the audio file isn’t found. If it is found then people see an ON button. The error message can be clicked on to reload the page. I want it to remain on the current active drop down menu page. Right now it makes you reselect an option from the drop down menu.

<!--I coult not get the page to display properly by putting the JS code here. That is why it's in the html field-->
<!--I coult not get the page to display properly by putting the css code here. That is why it's in the html field-->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.5.0-rc1/jquery.mobile-1.5.0-rc1.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.5.0-rc1/jquery.mobile-1.5.0-rc1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<style>
.hidden {
    display: none;
}
</style>

<style>
.down {
  font: bold 15px Arial;
  background-color:  red;
  color: white;
  padding: 3px 3px;
  width: 100%;
  text-decoration: none;
  display: inline-block;
  border-top: 5px solid red;
  border-right: 5px solid red;
  border-bottom: 5px solid red;
  border-left: 5px solid red;
}
</style>




<style>

select {
  border: 50px;
  color: #000000;
  background: #12f3fd;
  text-align: center;
  font-weight: bold;
 
  
  
  *background: Black;
  
}
</style>

</head>

<body>

<div align="center">
   <select name="stations" id="station" style="font-size:25px;" align="center">
    <option>Select a Opton</option>
    <option value="1">What you see if audio file was found</option>
    <option value="2">What you see if audio file was not found</option>
   
    
  </select>
</div>
<div class="st hidden" id="st1">
    <p>
    <audio id="audio1" src="example.mp3"></audio>
    
    <button id="A" class="button">ON</button>
    </p>
    </div>
    
    <div class="st hidden" id="st2">
    <p>
    <audio id="audio2" src="example.mp3"></audio>
    
    <button id="B" class="button">ON</button>
    </p>
    </div>


</body>


<!--Controls the Drop Down Menu-->
<script>
$(document).ready(function(){
    $('#station').on('change', function(){
        var theVal = $(this).val();
        $('.st').addClass('hidden');
        $('.st#st' + theVal).removeClass('hidden');
    });
});
</script>

<!--Displays the error message if the audio file is not found and gives the option to reload the page.-->

<div id="dwnB" class="down">

<script>
$("#audio2").on("error", function(e) {
document.getElementById("B").outerHTML = '<div id="dwnB" class="down" align="center" onclick="location.reload();"><h2><b>The Audio File Could not be found.</h2> Please try again later.<br> Tap anywhere on this message to reload and try again.</b></div>';
        
});
</script>
</div>

<!--This script reloads the page and is tied to the above script-->

<script>
const reloadtButton = document.querySelector("#reload");
// Reload everything:
function reload() {
    reload = location.reload();
}
// Event listeners for reload
reloadButton.addEventListener("click", reload, false);
</script>

</html>

I get this when i run the snippet.

Error: {
  "message": "Uncaught ReferenceError: reloadButton is not defined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 123,
  "colno": 1
}

Remember, Reload button is not in the body of the page but is in the script part of the page and only displays if there’s an error. Even though button A in the first menu option should error as well. I did not write a script for it to do that so you can see what it looks like with out the error.

Here is the script for the reload button.

<!--Displays the error message if the audio file is not found and gives the option to reload the page. The entire error message is the reload button.-->

<div id="dwnB" class="down">

<script>
$("#audio2").on("error", function(e) {
document.getElementById("B").outerHTML = '<div id="dwnB" class="down" align="center" onclick="location.reload();"><h2><b>The Audio File Could not be found.</h2> Please try again later.<br> Tap anywhere on this message to reload and try again.</b></div>';
        
});
</script>
</div>

<!--This script reloads the page and is tied to the above script-->

<script>
const reloadtButton = document.querySelector("#reload");
// Reload everything:
function reload() {
    reload = location.reload();
}
// Event listeners for reload
reloadButton.addEventListener("click", reload, false);
</script>

Reloading in the snippet causes the page to go blank. But if you run the code and reload somewhere else it displays as if you haven’t chosen a menu option yet.

I don’t know where “filename”: “https://stacksnippets.net/js”, is coming from as I don’t see that in my code.

How can I get to to stay on the current selected menu option after the reload button is clicked?

Javascript – How to show hide dropdown value based on boolean?

How can I add if condition within the code so that I can show/hide the value based on boolean?

I have defined boolean variable isEnable. Based on the value of isEnable, I want to display dropdown value <option value="Close"> Close Amount</option>.

Account.js

var isEnable = false;

    "columns":[
    {
      "title": "Amount",
      "render": function (data, type. full){
         if(data.full_access){
          return 'select class="selection dropdown_md" data-status="'+full.onlineStatus+'" data-value"'+full.onlineId+'">
    <option value="">Select Amount</option>
    <option value="Close"> Close Amount</option>
      }
     } 
    } 
    ]

Why is splice deleting my entire array? I would only like to delete max if it is in position 0

I’m working on a leet code problem with the following instructions:

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

In my code below, I expect to remove the Max number from the array only if it’s in index 0 of the array. When checking the debugger, I see that the entire array is deleted except index 0. Why is splice not working as intended?

what debugger shows
leetcode debugger view showing the entire array deleted

 var maxProfit = function(prices) {
        let theMin = Math.min(...prices)
        let minPosition = prices.indexOf(theMin)
        let theMax = Math.max(...prices)
        let maxPosition = prices.lastIndexOf(theMax)
        
        
        if (maxPosition === 0) {
            prices = prices.splice(0, 1)
            if (prices.length === 0) {
                return 0
            }
            
            maxProfit(prices)
        }
        
       
        
        return theMax - theMin
        
    };

TypeError: Cannot read properties of undefined JSON [duplicate]

I get TypeError: Cannot read properties of undefined (reading 'mentions') in from JS when I query the JSON from Twitter v2 API, presumably because the value is empty. How do I check if there are no mentions?

if (JsonData.entities.mentions) {
  JsonData.entities.mentions.forEach((mention) => {
    text = text.replace(
      `@${mention.username}`,
      `<a target="_blank" rel="noreferrer noopener" href="https://twitter.com/${mention.username}">@${mention.username}</a>`
    )
  })
}