Implement Tab Screen in React Native

I’m facing a weird problem. In my react native app I have a return <Tab.Navigator> which contains <Tab.Screen>. The problem shown in the image is not properly implemented, I tried putting padding in every tab Screen but it does not work, when I tried landscaping my Emulator the text and icon will scattered, can anyone help me with this, thanks in advance.

Portrait

enter image description here

Landscape

enter image description here

import { COLORS, FONTS, icons } from "../constants"

const TabBarCustomButton = ({ children, onPress }) => {   //this is the design from thye circle shape in the image
  return (
    <TouchableOpacity
      style={{
        top: -30,
        justifyContent: 'center',
        alignItems: 'center',
        ...styles.shadow
      }}
      onPress={onPress}
    >
      <LinearGradient
        colors={[COLORS.primary, COLORS.secondary]}
        style={{
          width: 70,
          height: 70,
          borderRadius: 35
        }}
      >
        {children}
      </LinearGradient>

    </TouchableOpacity>
  )
}

return (

<Tab.Navigator
  screenOptions={{
    tabBarShowLabel: false,
    tabBarStyle: [
      {
        display: "flex"
      },
      null
    ],
    headerShown: false
  }}
  tabBarOptions={{
    showLabel: false,
    style: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      elevation: 0,
      backgroundColor: COLORS.white,
      borderTopColor: "transparent",
      height: 100
    }
  }}
>
  <Tab.Screen
    name="Home"
    component={FeedStack}
    options={{
      tabBarIcon: ({ focused }) => (
        <View style={{
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Image
            source={icons.home}
            resizeMode="contain"
            style={{
              width: 25,
              height: 20,
              tintColor: focused ? COLORS.
                primary : COLORS.black
            }}
          />
          <Text style={{
            color: focused ? COLORS.
              primary : COLORS.black, ...FONTS.body5
          }}
          >HOME</Text>
        </View>
      )
    }}
  />
  <Tab.Screen
    name="Portfolio"
    component={MessageStack}
    options={{
      tabBarIcon: ({ focused }) => (
        <View style={{
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Image
            source={icons.pie_chart}
            resizeMode="contain"
            style={{
              width: 25,
              height: 20,
              tintColor: focused ? COLORS.
                primary : COLORS.black
            }}
          />
          <Text style={{
            color: focused ? COLORS.
              primary : COLORS.black, ...FONTS.body5
          }}
          >PORTFOLIO</Text>
        </View>
      )
    }}
  />
  <Tab.Screen
    name="Transaction"
    component={ProfileStack}
    options={{
      tabBarIcon: ({ focused }) => (
        <Image
          source={icons.transaction}
          resizeMode="contain"
          style={{
            width: 25,
            height: 20,
            tintColor: COLORS.white
          }}
        />
      ),
      tabBarButton: (props) => (
        <TabBarCustomButton
          {...props}
        />
      )
    }}

  />
  <Tab.Screen
    name="Prices"
    component={ProfileStack}
    options={{
      tabBarIcon: ({ focused }) => (
        <View style={{
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Image
            source={icons.line_graph}
            resizeMode="contain"
            style={{
              width: 25,
              height: 20,
              tintColor: focused ? COLORS.
                primary : COLORS.black
            }}
          />
          <Text style={{
            color: focused ? COLORS.
              primary : COLORS.black, ...FONTS.body5
          }}
          >STATS</Text>
        </View>
      )
    }}
  />
  <Tab.Screen
    name="Settings"
    component={ProfileStack}
    options={{
      tabBarIcon: ({ focused }) => (
        <View style={{
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Image
            source={icons.settings}
            resizeMode="contain"
            style={{
              width: 25,
              height: 20,
              tintColor: focused ? COLORS.
                primary : COLORS.black
            }}
          />
          <Text style={{
            color: focused ? COLORS.primary : COLORS.black, ...FONTS.body5
          }}
          >SETTINGS</Text>
        </View>
      )
    }}
  />
</Tab.Navigator>
);

Simon Says Random Sequence Flash – This code is just not running. I’ve tried to rewrite and clean up the flash sequence, but no luck. Any tips?

Having trouble figuring out why sequence will not flash and why game will not run correctly. Trying to have each square flash in a random pattern (incrementing pattern by one square). Code went from flashing only one square to simultaneously flashing all the squares and now flashing no squares. Any help would be appreciated.

let indigo = document.querySelector('#indigo')
let orange = document.querySelector('#orange')
let yellow = document.querySelector('#yellow')
let pink = document.querySelector('#pink')
    
        let gameVariables = {
            currentGame: [],
            level: 0,
            squares: [indigo, orange, yellow, pink]
        }
    
        //Enter your name to play the game
        let enterName = () => {
            let playerName = prompt('Enter your name!', 'Name')
            if (playerName != null) {
                document.querySelector('.player-name').innerHTML = 'Player: ' + playerName
            }
        }
    
        //Start
        let levelHTML = document.querySelector('.level')
        let gameStartButton = document.querySelector('#start')
        let start = () => {
            levelHTML.innerHTML = 'Level: ' + gameVariables.level
            gameStartButton.style.display = 'none';
            beginGame()
            }
            gameStartButton.addEventListener('click', start)
    
        //Restart
        let restartButton = document.querySelector('#restart')
        let restart = () => {
            gameVariables.level
            gameVariables.currentGame = []
            enterName()
            incrementLevel()
        } 
        restartButton.addEventListener('click', restart)
    
    
        //Begin Game
        let beginGame = () => {
            restart()
        }
    
        //Each random sequence will flash a random pattern
        let coloredSquares = document.querySelectorAll('.square')
        const flashSquare = () => {
            let i = 0;
            let computerPlays = setInterval(function() {
                playGame(gameVariables.currentGame[i])
                i++
                if (i >= gameVariables.currentGame.length) {
                    clearInterval(computerPlays)
                }
            }, 500)
            clearPlayerMoves()
        }
    
    
        //Audio
        soundsOfSquares = {
            indigo: new Audio('sounds/indigo.wav'),
            orange: new Audio('sounds/orange.wav'),
            yellow: new Audio('sounds/yellow.wav'),
            pink: new Audio('sounds/pink.wav')
        }
    
        let sound = (color) => {
            switch(color) {
                case indigo:
                soundsOfSquares.indigo.play();
                break;
                case orange:
                soundsOfSquares.orange.play();
                break;
                case yellow:
                soundsOfSquares.yellow.play();
                break;
                case pink:
                soundsOfSquares.pink.play();
                break;
            }
        }
    
        //Random pattern
        let randomSquares = () => {   
            const random = (Math.floor(Math.random() * gameVariables.squares.length))
            gameVariables.currentGame.push(gameVariables.squares[random])
            flashSquare()
        }
    
    
        const squaresArray = Object.values(coloredSquares)
    
        let numFlash = 0
        const playGame = (squaresArray, numFlash) => {
            let chosenSquare = squaresArray[randomSquares()]
            chosenSquare.className = 'active'
          setTimeout(() => {
              chosenSquare.classList.remove('active')
             if (numFlash < 5) {
                 numFlash += 1s
             playGame(squaresArray, numFlash);
              }
             }, 250);
        }
    
        //Player moves
        let clearPlayerMoves = () => {
            player = []
        }
        let playerMoves = (color) => {
            let sequence = '#' + color
            player.push(color)
            playerTurn(color)
        }
    
        let playerTurn = () => {
            if (player[player.length-1] !== currentGame[player.length-1]) {
            let compare = (player.length === currentGame.length) 
            if (compare) {
                if (level === 10) {
                    alert('Congratulations! You have beat Mushu at his own game')
                } else {
                    alert('Play the next level!')
                    nextLevel()
                }
                }
            }
        }
        let newLevel = () => {
            incrementLevel()
        }
    
        let incrementLevel = () => {
            gameVariables.level++
            levelHTML.classList.add('active')
    
            setTimeout(() => {
                levelHTML.classList.remove('active')
            }, 300)
            randomSquares()
        }
    beginGame()
    
    
    
    
    h1 {
            text-align: center;
            font-family:Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
        }
    
        body {
            background-image: url('background.png');
            background-color: black;
            text-align: center;
        }
    
        .button {
            text-align: center;
            margin: auto;
            padding: 10px;
        }
    
        #start {
            text-align: center;
            width: 20vw;
            height: 5vh;
            font-size: 20px;
            background-color: azure;
            font-style: bold;
            
        }
    
        .player-name {
        text-align: center;
        }
    
    
        .game-board {
            display: grid;
            grid-template-rows: repeat(2, 120px);
            grid-template-columns: repeat(2, 120px);
            justify-content: center;
        }
    
        .square {
            border: 1px solid black;
            cursor: pointer;
        }
    
        .square:hover {
            box-shadow: inset 0px 0px 5px 5px aqua;
        }
    
    
        #indigo {
            background-color: indigo;
        }
    
        #orange {
            background-color: orange;
        }
    
        #yellow {
            background-color: yellow;
        }
    
        #pink {
            background-color: hotpink;
        }
    
        .active {
            background-color: white !important;
    }
    
    
    
    <!DOCTYPE html>
        <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">
            <script src="app.js" defer></script>
            <link rel="stylesheet" href="style.css">
            <title>Mushu Says...</title>
            <link rel="icon" sizes="228x228" href="favicon.jpg">
        </head>
        <body>
            <h1>Mushu Says...</h1>
    
            <button id="start">Start</button>
         <div id="nameModal" class="modal">
                <div class="modalText-content">
                    <span class="close">
                        <p></p>
                    </span>
                </div>
            </div>
        <div>
            <h4 class="player-name">Player</h4>
            <h4 class="level">Level</h4>
    
         </div>
    
         <div class="game-board">
                <div class="square" id="indigo"></div>
                <div class="square" id="orange"></div>
                <div class="square" id="yellow"></div>
                <div class="square" id="pink"></div>
          </div>    
            
        <div class="button">
                <button id="restart">Restart</button>
        </div>
    
        </body>
    </html>

Add children to a react component following depth-first traversal

How can you append children to already declared React elements?

const MyElement = <SomeComponent/>;
MyElement.append(<SomeChild />);
MyElement.append(<AnotherChild />);

An example:

Let’s say you’re trying to render a ‘tree’ list, for example a file-navigation where you have an arbitrary number of sub-lists.

Now if you want to this in a depth-first manner, you need a reference to existing nodes, and be able to append children to them.

Example data structure:

Let’s assume a bunch of nested Maps here. Each key is a file or folder. Their value is a map of their children.

{
  [Folder_1] => {
    [Folder_1.1] => {
       [File_1.1.1] => null
    }
    [Folder_1.2] => {
       [Folder_1.2.1] => {
         [File_1.2.1.1] => null
       }
       [File_1.2.2] => null
    }
  }
}

Now the React output we want is this:

<FileNavigator>
  <Node node={Folder_1}>
    <Node node={Folder_1.1}>
      <Node node={File_1.1.1}>
    </Node>
  </Node>
  <Node node={Folder_1.2}>
    <Node node={Folder_1.2.1}>
      <Node node={File_1.2.1.1}>
    </Node>
    <Node node={File_1.2.2}>
  </Node>
</FileNavigator>

Note on existing SO answers:

  • How to append child to React element?: The answers in this one focus on React.createElement letting you pass a ‘children’ prop. React.createElement doesn’t work for ‘depth-first’ additions, since it assumes you know all the children at the time the method is called.

my useEffect is in an infinite loop and i dont know why

my code is

  const Weather = ({lat, lng}) => {
    console.log('%cApp.js line:37 lat, lng', 'color: #007acc;', lat, lng);
    useEffect (() => {
      axios
        .get(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=cc76bb943e6b3254cef79ff11e899572`)
        .then(response => {
          setWeather(response.data)
        }
      )
    }, [])
    
    console.log (weather)
    return (<h1>hi</h1>)

  }

weather function is running in an infite loop. eventhough i am passing an empty object at the end of useEffect. i have 0 clue as to what might be causing this problem.

const CountryDetails = ({ countryData }) => {
    console.log("countryData:", countryData)
    console.log('%cApp.js line:80 countryData.latlng[0]', 'color: #007acc;', Math.round(countryData.latlng[0]));
    console.log('%cApp.js line:81 countryData.latlng[1]', 'color: #007acc;', Math.round(countryData.latlng[1]));
    return (
     
      <>
        <h1>{countryData.name.common}</h1>
        <br></br>
        <p>{countryData.capital}</p>
        <p>{countryData.area}</p>
        <h3>Languages</h3>
        <ul>
          {Object.values(countryData.languages).map((language) => <li key={JSON.stringify(language)}><p>{JSON.stringify(language)}</p></li>)}
        </ul>
        <img src={countryData.flags.png} alt="country flag"></img>
        <div>
          {<Weather lat = {Math.round(countryData.latlng[0])} lng = {Math.round(countryData.latlng[1])}/>}
        </div>
      </>
    )
  }

 const Weather = ({lat, lng}) => {
    console.log('%cApp.js line:37 lat, lng', 'color: #007acc;', lat, lng);
    useEffect (() => {
      axios
        .get(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=cc76bb943e6b3254cef79ff11e899572`)
        .then(response => {
          setWeather(response.data)
        }
      )
    }, [])
    
    console.log (weather)
    return (<h1>hi</h1>)

  }

the code that is triggering the weather function.

Make browser back button show login page without error div

I have a Login jsp that takes user email and sends it to servlet. If the email is not in database, the servlet redirects back to Login.jsp with an attribute “error”. In the Login.jsp header I already have a scriplet that checks for this attribute and if it is set, it makes error msg div “display: block”, else it makes “display:none”. In this error msg I have a button with javascript to redirect to register page.

My Problem is:
If I press browser back button when in register page, it shows login page still with the error message. I want it to instead show login page without error msg div.

Multi dependent dropdown populate based on previous dropdown selected values using flask python and mysql

in my webpage i have five dropdowns ,in which the data is getting from only single mysql table.
whenever i load page ,first dropdown gets filled with data from mysql table, and when i select data from first dropdown then second dropdown value to be displayed based on selection of first dropdown value from mysql .
same thing for third dropdown ,it has to populate values based on selection of values two dropdown and fourth dropdown value to be displayed based selection of previous values from three dropdown and similar thing to fifth dropdown also , all these dropdown are interrelated to previous dropdown selection values. These all data is populated from only single table.
i have coded for first dropdown it is automatically populating data from mysql table ,and when i select value from first dropdown second dropdown is populated based on first dropdown value.But i not getting data in third dropdown based on selection of values from previous dropdowns.

      this is my .py file

mysql=MySQL()
models = Blueprint('models', __name__)

@models.route('/stk',methods=['POST','GET'])
def stockk():
    cur=mysql.connection.cursor()
    cur.execute("SELECT distinct vehicle FROM options_eod")
    stk=cur.fetchall()
    '''
    result=[]
    for row in stk:
        result.append("|".join(row))
    '''
    cur.close()

    return render_template('option_eod.html', stk=stk)

@models.route('/yeary/<get_stock>',methods=['POST','GET'])
def year(get_stock):
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT year FROM options_eod WHERE vehicle = %s", [get_stock])
    year = cur.fetchall()
    print(year)
    yearArray=[]
    for row in year:
        yearobj={'year':row['year']}
        
        
        yearArray.append(yearobj)
    print(yearArray)

    return jsonify({'yearlist':yearArray})

@models.route('/yeary/<get_stock>/<get_year>/',methods=['POST','GET'])
def exp(get_stock,get_year):
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute("SELECT distinct expecteddate FROM options_eod WHERE vehicle = %s AND year=%s", [get_stock,get_year])
    expr = cur.fetchall()
    print(expr)
    expArray=[]
    for row in expr:
        expobj={'expirydate':row['expirydate']}

        expArray.append(expobj)
    print(expArray)
    return jsonify({'explist':expArray})

this is my .html file

 {% extends 'index.html' %}
    {% block title %} sample tables {% endblock%}
    {% block head %}
    <link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/table.css') }}">
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    {% endblock %}
    
    {% block container %}
    <p></p>
    <div class='box'>
        <!-- /a is route url for home() in auth.py -->
    <form action="/stk" id="test" method='post'>
        <!--
            <input type="text" id="txtname" class="txtname" name="name" style="width: 20ch;margin-left: 1%" />     -->
        <select name="stkname" class="expr" id='stock'> 
            <option disabled selected > select stock</option>
            {% for st in stk %}
                <option value= "{{ st[0] }}" > {{st[0]}} </option>
            {% endfor %}  
    
        </select>    
        <select name="year" class="yr" id='yeary'> 
            <option disabled selected > select year</option>
            
            <!--    
        <option style='display:none;width:200px'></option> 
        <option disabled selected > select date</option> -->
        </select>
        <select name="exp" class="expr" id='expryy'> 
            <option disabled selected > select Expiry</option>
    
        </select>
        <!-- margin-left: gives margin space to submit from left side -->
        <select name="type" class="typ" id='optype'> 
            <option disabled selected > option type</option>
    
        </select>
        <select name="strike" class="strk" id='strkprice'> 
            <option disabled selected > strike price</option>
        </select>
        <label for='date'>select date</label>
        <input type='date' name='date' id='datee'/>
        <input type='submit' id='submit' value='submit' name='submit' style='height: 35px;margin-left: 2%;font-size: :30px' />
    
    </form>
    </div>
    <p></p>
    <div class='content'>
        {{dt}}
    </div>
    <script>
        //id  of <select>
    stock_select = document.getElementById('stock');  
    year_select = document.getElementById('yeary');
    expiry_select = document.getElementById('expryy');
    optype_select = document.getElementById('optype');
    strike_selct = document.getElementById('strkprice');
     
    stock_select.onchange = function(){
     stock = stock_select.value;
    console.log(stock);
     fetch('yeary/' + stock).then(function(response){
      response.json().then(function(data) {
       optionHTML = '';
       for (yrr of data.yearlist) {
        optionHTML += '<option>' + yrr.year + '</option>'
       }
       year_select.innerHTML = optionHTML;
      });
     });
    }
    
    
  year_select.onchange = function(){
 stock = stock_select.value;
 console.log(stock)
 year=year_select.value;
 alert(year);
 fetch('expiry/' + stock + '/'+ year +'/').then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (exp of data.explist) {
    optionHTML += '<option>' + exp.expirydate + '</option>'
   }
   expiry_select.innerHTML = optionHTML;
  });
 });
}
    
    </script>
    
    
    {% endblock %}

my sql table looks like

vehicle  expecteddate  range color  discount       date     size    year
   car    2/24/2022    240   blue       70      2/18/2022    100    2022
   car    2/24/2022    240   red        80      2/18/2022    100    2022
   car    3/15/2022    240   blue        90     2/18/2022    100    2022
   car    3/15/2022    240   red        60      2/18/202     100    2022
   car    4/20/2022    240  blue        40      2/18/2022    100    2022
   car    4/20/2022    240   red        50      2/18/2022    100    2022
   bus    2/24/2022    300  blue       120      2/18/2022    150    2022
   bus    2/24/2022    300   red       110      2/18/2022    150    2022
   bus    3/15/2022    300  blue       130      2/18/2022    150    2022
   bus    3/15/2022    300   red       140      2/18/2022    150    2022
   bus    4/20/2022    300  blue        80     2/18/2022     150    2022
   bus    4/20/2022    300   red        90     2/18/2022     150    2022
   car    2/24/2022    240  blue        60     2/17/2022     100    2022
   car    2/24/2022    240   red        40     2/17/2022     100    2022
   car    3/15/2022    240  blue        50     2/17/2022     100    2022
   car    3/15/2022    240   red        30     2/17/2022     100    2022
   car    4/20/2022    240  blue        70     2/17/2022     100    2022
   car    4/20/2022    240   red        45     2/17/2022     100    2022
   bus    2/24/2022    300  blue       130     2/17/2022     150    2022
   bus    2/24/2022    300   red       100     2/17/2022     150    2022
   bus    3/15/2022    300  blue       140     2/17/2022     150    2022
   bus    3/15/2022    300   red       120     2/17/2022     150    2022 
   bus    4/20/2022    300  blue        90     2/17/2022     150    2022
   bus    4/20/2022    300   red        30     2/17/2022     150    2022

year is not constant here it is based on current year and for next year it will be 2023
i am populating data from only one single table in mysql

Need best case senario

My input is const

input = [
  ["A", "B", "C", "D"],
  ["a", "b", "c"],
  [1, 2, 3, 4, 5, 6]
 ];

// Expected output

const output = ["A", "a", 1, "B", "b", 2, "C", "c", 3, "D", 4, 5, 6];

So I write a javascript code to achieve output,

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};
let lengthInputArray = input.lenght;
let outputArray = [];
let lengthArray = [];
for(let indexInput = 0; indexInput < input.length; indexInput++){
  lengthArray.push(input[indexInput].length);
}
let maxLen = Math.max(...lengthArray);

for(let maxIndex = 0; maxIndex < maxLen; maxIndex++){
  for (var indexArr of input) {
    if(indexArr.length <= maxLen){
      var tobeInsertValue = indexArr[maxIndex];
      if(tobeInsertValue != undefined){
        outputArray.push(tobeInsertValue);
      }
    }
  }
}
console.log("outputArray : " + outputArray);

Can anybody suggest me about good solution or optimum way to solve the problem?

delay between for loop iterations

Issue

I have a function that takes a list of strings, loops over them and prints each one to a new line.
I have added in some CSS animations that take a few seconds to have the string fully displayed.

The issue I am facing is that I can’t figure out a way to wait for the previous string to be fully displayed before beginning the animation of the next string. I’ve added a snippet below – sorry if I’m not explaining it well.

Intended Outcome

For each string in the array that we pass into the newComputerMessage(messages) function, it should print a new line but only after the previous line has completely been displayed.

let userInputs = [];
const textBox = document.querySelector(".textBox");
const userInput = document.querySelector(".userInput");
const letters = /^[A-Za-z]+$/;
let user = {
  name: "",
  timeInterval: -1,
  halt: false,
  quit: false
};

function captureUserInput() {
  let text = userInput.value;
  userInput.value = "";
  return text;
}

function nameEntered() {
  enteredName = captureUserInput();
  if (!enteredName.match(letters)) {
    newComputerMessage(">>Please only use Letters");
  } else {
    user.name = enteredName;
    newComputerMessage([">>Hello there " + user.name, ">>Second message"]);
  }
}

function newComputerMessage(messages) {
  for (let index = 0; index < messages.length; index++) {
    const newPElement = document.createElement("p");
    newPElement.innerHTML = messages[index];
    newPElement.setAttribute("class", "computerText");
    textBox.appendChild(newPElement);
  }
}
.textBox {
  width: max-content;
}

.computerText {
  color: black;
  font-family: monospace;
  overflow: hidden;
  border-right: 0.15em solid orange;
  white-space: nowrap;
  margin: 0 auto 0 0;
  letter-spacing: 0.15em;
  animation: typing 3.5s steps(30, end), blink-caret 0.5s step-end infinite;
  width: max-content;
}

/* The typing effect */
@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: orange;
  }
}
<body>

  <div class="displayScreen">
    <div class="textBox">
      <p class="computerText">>>Hello, please enter your name below</p>
    </div>

  </div>

  <div class="appInput">
    <input class='userInput' type="text" name="fname"><br>
    <input onclick="nameEntered()" class="button" type="submit" value="Submit">
  </div>
  </div>

</body>

React router dom Link navigate to page on the same level OR replace only the end of current URL

I am using <Link/> from react-router-dom for navigation. And I wanted to switch the page at the curent level I am at, meaning to only change the last endpoint.

I have a url structure with the following hierarchy

/animals/cat
/animals/dog

And I wanted to go to dog while I am in the cat page using <Link/> and vice versa.
Is there an easier way to change only the last endpoint cat to dog when using link in the page?

I tried the following

This append /dog at the end of whatever url I am at

<Link to="./dog">   //leads to the url /cat/dog  instead of /animals/dog
<Link to="dog">     //leads to the url /cat/dog  instead of /animals/dog

And this replace everything on the url to /dog

<Link to="/dog">    //leads to the url /dog      instead of /animals/dog
<Link to="../dog">  //leads to the url /dog      instead of /animals/dog

Is there an easy way to do this on the Link component itself instead of using hooks or some other methods?

How to capture the window close event on Electron’s renderer process?

On a classic front-end JavaScript, capturing the “window close” event can be done in a multiple ways. It can be done with:

// Method A: `close` event via an event listener
window.addEventListener( 'close', function(event){ /** your magic here **/ } )

// Method B: `beforeunload` event via an event listener
window.addEventListener( 'beforeunload', function(event){ /** your magic here **/ } )

// Method C: classic `onclose` event binder
window.onclose = function(event){ /** your magic here **/ }

// Method D: classic `onbeforeunload` event binder
window.onbeforeunload = function(event){ /** your magic here **/ }

I tried these methods inside the Electron’s renderer script/environment but the window close event doesn’t seem to get triggered.

Which brings to my question, how to capture the “window close” event on Electron’s renderer process?

Stringified toLocalTimeString based on server timezone instead of parameter timezone

Super weird behavior here:

I have a variable that is a Date object, and when I print it to the terminal, it shows ‘2022-05-05T17:00:00.000Z’. As soon as I run it through toLocaleString(), it converts the Date to the time where the server is running from, instead of the passed in timezone.

let date1 = momentDate.toDate() // when I print this to terminal, it shows 2022-05-05T17:00:00.000Z as highlighted text (indicating it's an object).
let date2 = date1.toLocaleString("en-US", { timezone: 'Europe/Lisbon' }) // this should make it show up as 6:00 PM. (Because 17:00 Z/UTC = 18:00 Lisbon time, and converting that to "en-US" shows it in the 12 hour clock format)

Instead, it outputs to the console like this, indicating that it’s using the EST timezone for the conversions, where my server is based. (17:00 Z/UTC = 13:00 EST = 1:00 PM):

5/5/2022, 1:00:00 PM

How do I fix this?

How to have Prettier format two JSX and JS separately within the same file in React

Is there any way to have Prettier format JavaScript differently than the JSX in React in the same file, mainly just making the tabWidth for JS 4 and for JSX 2?

Should I be changing the file extension to .jsx and not .js, or will this at least make it so that if I move all my components to be rendered entirely in their own file with props, I can call those .jsx files and it will format them with tabWidth 2 and then keep functions and other things in a separate JS file that will be formatted with tabWidth 4?

Is there a way to draw hundreds of points faster (p5.js)

I am making a program to test out my attempt at a Perlin Noise generating algorithm. The Perlin noise itself seems fine, however I’ve found that drawing that noise on the canvas is very slow. This is probably because for every single point in the canvas I have to call the stroke() function to change the color of the next pixel, then draw that pixel. This is done over a 400*400 pixel canvas, so I am changing the color with stroke() 1,600 times and calling point() 1,600 times.

This takes some time to do. I was wondering if there is any way of making this faster. Perhaps if I could turn the Perlin noise into an image, then load that image instead of drawing all 1600 points individually?

The code of my draw loop is below

function draw() {
  background(220);
  strokeWeight(1);
      
  for(var row = 0; row < height; row ++)
  {
    for(var column = 0; column < width; column ++)
    {
      //takes a noise value from the myNoise array whose elements have a range of [-1,1] and turns it into a value from [0,256], and makes that the color of the next point
      stroke((myNoise[row][column]+1)*128);
      
      point(column,row)
    }
  }
    
  noLoop();
}