React not redirecting as intended when A function is called in the Routes route

I am building a login and logout system for a react project of mine. I have a navbar setup and I am using react-redirect-dom to create links and redirect links to different pages in order to manage the login system.

In the current project, I have a route that does the processing for the login in the login component. I have another link that processes the signup within the signup component.

For the logout, If a user is logged in and they use the /logout endpoint, I want it to immediately call the handleLogout function and log the user out and reroute to the / endpoint

Here is the code I have and the error:

function App() {

  const [loggedIn, setLoggedIn] = useState(false)
  const [currentUser, setCurrentUser] = useState('')

  function handleLogout() {
    console.log('handle logout')
    axios.post('/api/auth/logout', {
      "username":currentUser.username,
      "password":currentUser.password,
    })
    .then((data) => {
      console.log(data.data)
      setCurrentUser(data.data)
      setLoggedIn(false)
      return(<Navigate to='/' />)
    })
    .catch((err) => {
      console.log(err)
    })
  }

  return (
    <div className="App">
      {/* <ContentContext value={contentContextValue}> */}
        <BrowserRouter>
          <Routes>
              <Route exact path="/" element={loggedIn ? <Feed/> : <Login setLoggedIn={setLoggedIn} setCurrentUser={setCurrentUser}/>} />
              <Route exact path="/login" element={<Login setLoggedIn={setLoggedIn} setCurrentUser={setCurrentUser}/>}/>
              <Route exact path="/signup" element={<Login setLoggedIn={setLoggedIn} setCurrentUser={setCurrentUser}/>}/>
              <Route exact path="/logout" element={loggedIn ? () => {handleLogout()} : <Login/>}/>
            </Routes>
        </BrowserRouter> 
      {/* </ContentContext> */}
    </div>
  );
}

Here is the error:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

The text is disappearing when i added the image

The text like “welcome” are not appearing when I added the av

<!DOCTYPE html>
<html>
    <style>
        @font-face {
            font-family: OpenSans;
            src: url(OpenSans-Bold.ttf);
         }
         
         * {
            font-family: OpenSans;
         }

    </style>
<body>
  <canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;">
    Your browser does not support the canvas element.
  </canvas>

  <script>
    var canvas = document.getElementById("myCanvas");
    var background = new Image();
    background.src = "https://i.imgur.com/ua7gL3M.png";
    let av = new Image();
    av.src = "https://cdn.discordapp.com/avatars/852848188942581764/6b54aba527059f96ecdcb06763d89dac.png?size=4096"

    // Make sure the image is loaded first otherwise nothing will draw.
    background.onload = function(){
        ctx.drawImage(background,0,0); 

        // The following lines were moved into the onload callback
        ctx.beginPath();
        ctx.arc(512,160,120,0,2*Math.PI);
        ctx.strokeStyle = "red"
        ctx.lineWidth = 15;
        ctx.stroke();
        ctx.closePath();
        ctx.clip();
        
        ctx.drawImage(av, 390, 40, 250, 250);

        ctx.beginPath();
        ctx.arc(405,160,120,0,2*Math.PI,true)
        ctx.clip();
        ctx.closePath();
        ctx.restore();
        //welcome
        ctx.fillStyle = "#00ffff";
        ctx.font = "90px OpenSans";
        ctx.shadowColor="black";
        ctx.shadowOffsetX = 3;
        ctx.shadowOffsetY= 3;
        ctx.shadowBlur= 10;
        ctx.textAlign = "center"
        ctx.fillText("WELCOME", (canvas.width / 2) , 360 );
        //username
        ctx.fillStyle = "#2ffa76";
        ctx.font = "50px OpenSans";
        ctx.shadowColor="black";
        ctx.shadowOffsetX = 3;
        ctx.shadowOffsetY= 3;
        ctx.shadowBlur= 10;
        ctx.textAlign = "center"
        ctx.fillText("Haruke#0001",(canvas.width / 2), 415);
        //thanks
        ctx.fillStyle = "#5076ff";
        ctx.font = "35px OpenSans";
        ctx.shadowColor="black";
        ctx.shadowOffsetX = 3;
        ctx.shadowOffsetY= 3;
        ctx.shadowBlur= 10;
        ctx.textAlign = "center"
        ctx.fillText("Thanks For Joining!!",(canvas.width / 2), 460);
    }
    var ctx = canvas.getContext("2d");
  </script>

</body>

</html>

HTML5 Video autoplay with sound unmuted

I need to implement a local autoplay video on my website. Still, I knew that newer browsers, i.e., Chrome, Mozilla, and Safari, have blocked autoplay when the video has no ‘muted’ attribute.
So,
Is there any way to autoplay the video unmuted(with sound) in HTML5 by any trick in HTML or Javascript?
Since, When I remove the ‘muted’ attribute, The video stops from autoplay by the Browser.

Here is the simple HTML5 code I use:

<body>
<div class="video-wrapper">
<video autoplay muted loop playsinline preload="metadata">
  <source src="EDMVideo(Jay)_NEW.webm">
</video>
</div>
</body>

Javascript fetch fails to call localhost

I cannot let javascript fetch a localhost

contentAPI.php

<?php
echo 'en';
?>

curl call

curl http://localhost:8000/CONTENT/contentAPI.php

curl result

en

javascript call

fetch("http://localhost:8000/CONTENT/contentAPI.php")
        .then(function(response) {
            return response.text();
        })
        .then(function(responseText) {
            alert(responseText);
        })
        .catch(function(err) {
            alert(err);
        });

javascript result

TypeError: Failed to fetch

Any help?

On iOS, is there a way to detect a web page runs in the embedded browser and open the “real” one?

My web site uses magic links for login, however, I have a problem on mobile (not sure about Android – haven’t tried yet, but the problem exists at least on iOS): when a user receives the email say in the GMail app, the link opens in the embedded browser, meaning that cookies will not be passed to the “real” browser.

Is there a way to ensure the link in the email opens in the real system browser and therefore cookies are stored permanently?

(Essentially browser session isolation on iOS breaks a lot of things on the Internet, so surely there is a workaround?)

How do you solve a mathematical equation without using document.write?

Here is my code –

Inputting the following metrics:

Frame Width:  16
Frame Height:  20 
Picture Width:  11 
Picture Height:  17 
Mat Overlap:  .25

…produces the following output: 1.6252.625 due to not writing HTML after the calculation is made, thus should be:

Width = 1.625
Height = 2.625

{

    margin:0;

    padding: 0;

    font-family: 'Lato', sans-serif;

  }



  /*Fieldset and legend */

   fieldset {

     margin: 2em 0;

     padding: 1em 2em;

     border: solid 1px #ccc;

     border-radius: 6px;

     min-width:P 200px;

   }



   legend {

     font-size: 1.25em;

     padding: 0 .25em;

     color: #999;

   }



   /* Labels */

    label{

      display: block;

      margin-top: 1em;

    }



    .checks label {

          margin-top: 0;

       }



    label:first-of-type {

      margin-top: 0;

    }



    /* Inputs and textarea */

     input {

         padding: .5em;

         border: solid 1px #999;

         background-color: #D3D3D3

     }



     input[type="number"], input[type="text"] {

         width:  15em;

         background-color: #D3D3D3

     }



     textarea {

         min-height: 8em;

         min-width: 100%;

         padding: .5em;

         border: solid 1px #999;

         background-color: #D3D3D3

     }



     /* radio buttons and checkboxes */

      .checks {

        margin-bottom: 1em;

      }



      .checks p {

        margin-bottom: 0;

      }



      input[type="checkbox"] + label, input[type="radio"] + label

      {

        display: inline-block;

        padding-top: 0;

        margin-top: 0;

      }



      input[type="radio"] {

        margin-left: 1.5em;

        margin-right: 0;

      }



      input[type="radio"]:first-of-type {

        margin-left: 0;

      }

      #dvemail {
        display: none;
      }
      #chkYes:checked ~ #dvemail {
        display: block;
      }



      /* Submit Button */

       input[type="button"] {

         padding: .5em 1em;

         border-radius: 6px;

         background-color: #333;

         color: #fff;

         font-family: 'Lato', sans-serif;

         font-size: .8em;

       }



       /* Large screen rules */

       @media screen and (min-width: 430px) {

            legend {

              font-size: 1.75em;

            }



            fieldset {

              width: 40%;

              min-width: 320px;

              margin: auto;

            }



            .checks label {

              display: inline-block;

              padding-top: .5em;

              margin-top: 0;

              margin-right: .5em;

            }

       }
<!DOCTYPE html>

<html lang="en">

    <head>
    
        <meta charset="UTF-8">

        <meta name "viewport" content="width=device-width,

        initial-scale=1.0">

        <title>I Was Framed - Calculator</title>



        <link href="https://fonts.googleapis.com/css?family=Lato:300,400,400i,700,900&display=swap" rel="stylesheet">

        <link rel="stylesheet" href="style.css">

    </head>

<body>

<section>

<form id="frm1" action="form_action.asp">

<fieldset>

<legend>

I Was Framed Calculator

</legend>



<label for="frameWidth">Frame Width:</label><input type="number" step="any" min="0" name="wf" id="wf">

<label for="frameHeight">Frame Height:</label><input type="number" step="any" min="0" name="hf" id="hf"><br>

<label for="pictureWidth">Picture Width:</label><input type="number" step="any" min="0" name="wp" id="wp">

<label for="pictureHeight">Picture Height:</label><input type="number" step="any" min="0" name="hp" id="hp"><br>

<label for="matOverlap">Mat Overlap:</label><input type="number" min="0" step="any" name="o" id="o"><br>

<div class="checks">
<br>
Email results? &nbsp&nbsp
    <input type="radio" id="chkYes" name="chk" />
    <label for="chkYes">Yes</label>
    
    <input type="radio" id="chkNo" name="chk" />
    <label for="chkNo">No</label>
    <div id="dvemail">
<br>
        Email:
        <input type="email" id="email" /><br>
        <label for="msg">Note:</label>
        <textarea name="msg" id="msg"></textarea>
    </div>

</div>

<input type="button" onclick="calc()" value="Calculate"/>

</fieldset>

</form>

</section>

<script>

function calc()

{

var wf = document.getElementById('wf').value

var hf = document.getElementById('hf').value

var wp = document.getElementById('wp').value

var hp = document.getElementById('hp').value

var o = document.getElementById('o').value

Width:  document.write((1/2)*(hf-hp+o));
Height: document.write((1/2)*(wf-wp+o));

}

</script>

</body>

</html>

I’m specifically wanting to solve the following two equations based on user input:

Width:  document.write((1/2)*(hf-hp+o));
Height: document.write((1/2)*(wf-wp+o));

But I want to avoid using document.write completely because I can’t seem to .write HTML after the calculation to have the output of my calculator look presentable. Respectfully, what should I use instead and how with my code provided?

I have also looked at JavaScript eval() but it asserts –

Do NOT use eval(). due to security issues.

Why item display undefine? [duplicate]

There is 3 different button, once the user clicks on the button it will come out random price, but it displays undefine

const prizes = ['toy1', 'toy2', 'toy3'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
// User click on each button
document.getElementById(`btn-${btnNum}`).addEventListener("click", function() {
// Winner
 alert("Congratulations you have won a " + prizes[btnNum] + "!");
});
}

Javascript Quiz displayQuestion Function not operating properly

I’m creating a javascript quiz for a class I’m in and I can’t get the qisplay Question function I’m running to return what I want. When I run it in the console it returns that ‘answerBtn.text content’ is null. I can get either the question to display or the answer buttons, but never both. What am I doing wrong?

    var quizButton = document.querySelector("#quiz-button")
var timer = 75
var quizTimer = document.querySelector("#quiz-timer")
var questionIndex = 0
var score = 0
var questionBoxElement = document.querySelector('#question-box')

var questions = [
    // add questions here!!
     // question 1
     {
        questionText:"This is question 1",
        options:["a. answer", "b. correct", "c. answer", "d. answer"],
        answer:"b. correct"
    },
    // question 2 
    {
        questionText:"this is question 2",
        options:["a. correct", "b. answer", "c. answer", "d. answer"],
        answer:"a. correct"
    },
    // question 3
    {
        questionText:"This is question 3",
        options:["a. answer", "b. answer", "c. answer", "d. correct"],
        answer:"d. correct"
    },
    // question 4 
    {
        questionText:"this is question 4",
        options:["a. answer", "b. answer", "c. correct", "d. answer"],
        answer:"c. correct"
    },
    // question 5
    {
        questionText:"this is question 5",
        options: ["a. answer", "b. answer", "c. correct", "d. answer"],
        answer: "c. correct"
    }
];
// display questions
function displayQuestion() {
    let question = questions[questionIndex];
    let answerOptions = question.options;

    let questionEl = document.querySelector("#question-box");
    questionEl.textContent = question.questionText;

    for (var i = 0; i < answerOptions.length; i++) {
        let answerChoices = answerOptions[i];
        let answerBtn = document.querySelector("#option"+i);
        answerBtn.textContent = answerChoices;
    }


    document.querySelector("#answer-buttons").addEventListener("click",checkAnswer);


    // determine if content for selected button and correct answer is the same 
    function correctAnswer(answerBtn){
        return answerBtn.textContent === question[questionIndex].answer;
    }
    
    // check to see if answer selected is correct
    function checkAnswer(event){
        let answerBtn = event.target; 
        // correct answer increases the score 
        if (correctAnswer(answerBtn)){
            score = score + 20;
        }
        // incorrect answer decreases the time remaining 
        else {
            if (timeLeft > 10){
                timeLeft = timeLeft - 10;
           }
           else{
               timeLeft = 0;
               endQuiz();
           }
        }
    
        // go on to next question 
        questionIndex++;
    
        // if there are no more questions, end quiz
        if (questionIndex < questions.length){
            displayQuestion();
        }
        else{
            endQuiz();
        }
    }
    
    document.querySelector("#answer-buttons").addEventListener("click", checkAnswer)









}
// timer countdown
function countdown() {
    var timeLeft = setInterval(() => {
        
        if (timer >= 0 || questionIndex < 5) {
            quizTimer.textContent = timer + " seconds left";
            timer --;
            questionIndex ++;
            
        }
        else {
            clearInterval(timeLeft);

            // call game over function
        }
    }, 1000);
}


//Start function
function startQuiz() {
    var startQuizIntro = document.querySelector(".start-quiz-intro")
    startQuizIntro.setAttribute("class", "hide")
    questionBoxElement.classList.remove("hide")
    // reset timer and score
    userScore = 0;

    countdown();
    displayQuestion();
}

// One Line to call one function
quizButton.addEventListener("click", startQuiz);

How to use push() into array json file when “mouse click”?

I only want to push() the array into the json file when “mouse click”, but when i use it as my code nothing show up. I know the node.js is working and the javascript is also working because i test a little experiment on the node.js before

Website for node.js test

https://www.youtube.com/watch?v=U57kU311-nE

how to fix this error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

Website for javascript and json

https://www.khanacademy.org/computing/computer-programming/programming/arrays/pt/modifying-arrays?

8.5: Saving Data to JSON File with Node.js – Programming with Text

https://www.youtube.com/watch?v=6iZiqQZBQJY?

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Oppai</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
  </head>

  <body>
    <script src="Array+json+node.js"></script>
  </body>
</html>

Array+json+node.js

function setup() {
    createCanvas(400, 400);
  }
  
  function draw() {
    background(220);

//var xPositions = [100, 200];
var fs = require('fs');
const { finished } = require('stream');
var data = fs.readFileSync('JsonFilePath1.json');
var xPositions = JSON.parse(data);
console.log(words);
//^ the new json

var draw = function() {
    if (mouseIsPressed) {
        xPositions.push(mouseX);
    }
    noStroke();
    background(212, 254, 255);
    
    stroke(64, 117, 207);
    fill(196, 33, 255);
    for (var i = 0; i < xPositions.length; i++) { 
        line(xPositions[i], 120, 194, 285);
        ellipse(xPositions[i], 104, 32, 46);
    }

//json write node.js
    var data = JSON.stringify(xPositions, null, 2);
    fs.writeFile('JsonFilePath.json', xPositions, finished);
    
    function finished(err) {
        console.log('all set.');
    }
    //^json write

};

  }
  

JsonFilePath1.json

[100, 200]

Anyone know how to show different Slick Slider images for each Product page within Shopify?

I was able to get a Slick Slider (kenwheeler.github.io/slick/) to show on my product pages, however it shows the same photos for every product. I need each product to show images related to the product on the Slick Slider.

I feel like in the Add Product module built into Shopify there needs to be a field to add media for the Slick Slider for each product.

Is this achievable?

Browserrouter redirect

I’m new to react.js. This is my question. This line browserHistory.push(“/Main”)
does not redirect to the main page after the successful login. Not sure the reason. Please help. I have already searched on the internet but couldn’t find one to solve my problem. The URL address bar shows http://localhost:3000/Main but it does not redirect to the main page.

App.js

import React from "react"
import Login from "./Login"
import Main from "./Main"
import  {BrowserRouter as Router,Route,Switch}  from "react-router-dom"

function App() {
  
  return (
    <Router>
      <div className="App">

        <Switch>
          <Route exact path="/" component={Login}></Route>
          <Route path="/main" component={Main}></Route>
        </Switch>
          
      </div>
    </Router>
  )
  
}
export default App

APIService.js

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class APIService extends Component{
    

    static InsertData(body){
        return fetch("/login",{
            'method':'POST',
              cache: "no-cache",
              headers : { 
                'Content-Type': 'application/json'
                
               
      },
      body:JSON.stringify(body)
    })
    .then(response=>{
        if(response.ok){
            return response.json()
            }
        }
        
    ).then(
        data=>{
            if(data["isLogin"]===1){
              console.log(data)
              browserHistory.push("/Main") // this line
            }
            
        }
    )
    .catch(error => console.log(error))
    }
}

allocation in array using textinput in react native

Create a Parking Management application in React Native where the application will:
~ Parking manager can create a lot: App will ask for the number of lots in the parking area, it will
then show the number of lots on the page for the parking area.
~ Each lot will be allotted a unique number.
~ App will ask for a car registration number while entering into the parking area and allot any
random parking lot to the car, If available.
~ If no lot is empty then show a toast message that Parking is full.

  • On exit, parking charges should be paid by the car and the parking lot will also be marked
    empty for other cars, Calculations for parking charges are:

  • First 2 hour

  • $10 will be changed for every hour then after

    this is my task and i did this

    my mainpage code
    export default class mainPage extends React.Component<any, any> {
    addValues: any
    parkingLot: any
    constructor(props: any) {
    super(props)
    this.state = {
    text: ”,
    slots: [],
    screen: ‘screen1’,
    vehicleNumber: ”,
    parkingLot: [],
    selectedSlot: ”,
    }
    }

    createSlot() {
      let tempdata: any[] = []
      for (let i = 0; i < parseInt(this.state.text); i++) {
        tempdata.push({
          allocated: false,
          timestamp: new Date(),
        })
      }
      this.setState(
        {
          slots: [
            ...this.state.slots,
            {
              id: (Math.random() + 1).toString(36).substring(7),
              count: parseInt(this.state.text),
              data: tempdata,
            },
          ],
          text: '',
          screen: 'screen2',
        },
        () => {
          this.props.navigation.navigate('floor', {
            slots: this.state.slots,
          })
        },
      )
    }
    
    park = () => {
      console.log('jcjhj', this.state.parkingLot)
      var item = this.state.slots[
        Math.floor(Math.random() * this.state.slots.length)
      ]
      console.log('Parkinglot', this.state.parkingLot, item)
      console.log('Slots', this.state.slots)
      if (this.state.slots) {
      }
    }
    renderItem(item: any) {
      return (
        <TouchableOpacity
          style={styles.Slotinput}
          onPress={() =>
            this.setState({ screen: 'screen3', selectedSlot: item.id })
          }
        >
          <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
            Slot ID:-{item.id}
          </Text>
          <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
            Slot Count:-{item.count}
          </Text>
        </TouchableOpacity>
      )
    }
    renderItem1(item: any) {
      return (
        <View style={styles.Slotinput}>
          <Text>{item.allocated ? 'Allocated' : 'Available'}</Text>
          {this.state.parkingLot.map((e: any) => {
            return <Text>{e.carnumber}</Text>
          })}
        </View>
      )
      //   )
      // }
      // return demo
    }
    
    render() {
      return (
        <View>
          {this.state.screen === 'screen1' && (
            <View style={styles.form}>
              <TextInput
                style={styles.input}
                placeholder="Enter A value for slot"
                onChangeText={(text: any) => this.setState({ text })}
                value={this.state.text}
              />
              <TouchableOpacity
                style={
                  this.state.text && this.state.text
                    ? styles.addItemButton
                    : styles.BlurItemButton
                }
                disabled={this.state.text == ''}
                onPress={() => this.createSlot()}
              >
                <Text style={styles.buttonText}>Submit</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
      )
    }
    

    }

    my 2nd page code

    export default class floor extends Component<any, any> {
    handleslot: any
    constructor(props: any) {
    super(props)

          this.state = {
            text: '',
            space: props.route.params.slots,
            screen: 'screen1',
            selectedSlot: '',
          }
        }
    
        sendArray = () => {
          let tempdata: any[] = []
          for (let i = 0; i < parseInt(this.state.text); i++) {
            tempdata.push({
              allocated: false,
              timestamp: new Date(),
            })
          }
          this.setState(
            this.props.navigation.navigate('parkingSlot', {
              space: this.props.route.params.slots,
            }),
          )
          // alert(this.state.space.length)
        }
    
        renderItem = (item: any) => {
          console.log(item.item)
    
          return (
            <TouchableOpacity style={styles.Slotinput} onPress={this.sendArray}>
              <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
                Slot ID:-{item.item.id}
              </Text>
              <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
                Slot Count:-{item.item.count}
              </Text>
            </TouchableOpacity>
          )
        }
    
        render() {
          return (
            <View>
              <Text onPress={() => this.props.navigation.navigate('MainPage')}>
                Back
              </Text>
    
              <FlatList
                data={this.props.route.params.slots}
                renderItem={this.renderItem}
                keyExtractor={(item) => item.id}
              />
            </View>
          )
        }
      }
    

my 3rd page

export default class parkingSlot extends Component<any, any> {
      constructor(props: any) {
        super(props)
        // console.log('parkingSlots::--', this.props.route.params.space[0].data)
    
        this.state = {
          text: '',
          parkingLots: [] = this.props.route.params.space[0].data,
          screen: 'screen1',
          selectedSlot: '',
          vehicleNumber: '',
        }
      }
      park() {
        // console.log('this.state.parkinglot', this.state.parkingLots)
    
        this.state.parkingLots?.every((vehicleNumber: any) => {
          console.log(vehicleNumber)
    
          if (vehicleNumber.isAllocated !== true) {
            vehicleNumber.isAllocated == true
            return false
          }
          return true
        })
        this.setState([...this.state.parkingLots])
      }
    
      renderItem = (item: any) => {
        console.log('Data', item)
    
        return (
          <TouchableOpacity style={styles.Slotinput}>
            <Text>{item.allocated}</Text>
          </TouchableOpacity>
        )
      }
      render() {
        return (
          <View>
            <Text onPress={() => this.props.navigation.goBack()}>Back</Text>
            <TextInput
              placeholder="Vechicle Number"
              style={styles.input}
              value={this.state.vehicleNumber}
              onChangeText={(vehicleNumber: any) =>
                this.setState({ vehicleNumber })
              }
              // onChangeText={data => this.setState({ vehicleNumber: data })}
            ></TextInput>
            <TouchableOpacity
              style={styles.addItemButton}
              onPress={() => this.park()}
            >
              <Text>Park Vechicle</Text>
            </TouchableOpacity>
    
            <FlatList
              data={this.props.route.params.space[0].data}
              renderItem={this.renderItem}
              keyExtractor={(item) => item.id}
            />
          </View>
        )
      }
    }

Cannot read properties of null (reading ‘innerHTML’) Even With Script Tag After All Elements In My Body Tag

I keep getting the Uncaught TypeError: Cannot read properties of null (reading ‘innerHTML’) error in my console with the script tag at the end of my body tag beneath all divs and other elements. The error is only on user & opponent divs in the HTML and with the userPic.innerHTML and oppPic.innerHTML

  <body>

        <div class="container">

            <div class="header">
                <h1 class="title">Codys Pokemon Game</h1>
            </div>

            <div id="game" class="game">
                <input class="gameBtn" type="button" onclick="choose1()" value="CLICK TO START">
                <input class="infoBtn" type="button" onclick="info()" value="CLICK FOR GAME INFO">
            </div>

            <div class="user"></div>
            <div class="opponent"></div>

        </div>
    <script src="script.js"></script>
  </body>

My script.js file shouldn’t have any errors but if it does, this is the part where I add a bunch of stuff to my HTML:

    gameHTML.innerHTML = `<h2 class="gameInfo">Choose Your Attack</h2>`
    gameHTML.innerHTML += `<div class="userHp"><br>Your Health: ${pokemon1[1]}</div>`
    gameHTML.innerHTML += `<input class="att1" type="button" onclick="attack1()" value="Use: Attack: ${curPmon[4]}">`
    gameHTML.innerHTML += `<input class="att2" type="button" onclick="attack2()" value="Use: Attack: ${curPmon[5]}">`
    gameHTML.innerHTML += `<input class="att3" type="button" onclick="attack3()" value="Use: Attack: ${curPmon[6]}">`
    gameHTML.innerHTML += `<div class="oppHp"><br>Opponent Health: ${curOpp[1]}</div>`
    userPic.innerHTML += curPmon[7]
    oppPic.innerHTML += `<img src="${curOpp[7]}" alt="${curOpp[0]}">`

These are the variables I have for the IDs:


var gameHTML = document.getElementById('game')
var userPic = document.getElementById('user')
var oppPic = document.getElementById('opponent')