An unknown bug doesn't allow the quotes app to work. What's the issue?

Joined
Sep 12, 2022
Messages
39
Reaction score
0
The current error that I am getting is caught TypeError: Cannot read properties of null (reading 'useEffect') I tried adding React to the start of every useEffect and useState method but it doesn't fix it. I've tried different scenarios but the issue persists. Any help with why this code isn't working?

HTML:
<!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">
    <title>React quote maker</title>
    <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
    <link rel="shortcut icon" href="quote logo.png" type="image/x-icon">
</head>
<body>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <div id="root"></div>
  <script type="text/babel">
    const { useEffect, useState } = React;
    import { createRoot } from 'react-dom';
    
    let quotesArr;
   useEffect(() => {
    fetch("https://type.fit/api/quotes")
      .then(res => res.json())
      .then(data => {
        quotesArr = data
        console.log("quotesArr")
        console.log(quotesArr)
        RandomQuotVal()
        RandomAuthVal()
        getRandomColor()
        Myapp()
      })
   }, [])

  const RandomQuotVal = () => {
    return (
      <>
        {quotesArr[Math.floor(Math.random() * quotesArr.length)].text}
      </>
    )
  }

  const RandomAuthVal = () => {
    return (
      <>
        {quotesArr[Math.floor(Math.random() * quotesArr.length)].author}
      </>
    )
  }

  const getRandomColor = () => {
    const letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return (
      color
    );
  };



  const Myapp = ({quotesArr}) => {
    const [quote, setQuote] = useState(quotesArr[0].text);
    const [author, setAuthor] = useState(quotesArr[0].author);

    useEffect(() => {
      const bgColor = getRandomColor();
      document.getElementById("main").style.backgroundColor = bgColor;
      document.getElementById("text").style.color = bgColor;
      document.getElementById("author").style.color = bgColor;
    }, [])

    const handleClick = () => {
      const randomIndex = Math.floor(Math.random() * quotesArr.length);
      setQuote(quotesArr[randomIndex].text);
      setAuthor(quotesArr[randomIndex].author);
      const bgColor = getRandomColor();
      document.getElementById("main").style.backgroundColor = bgColor;
      document.getElementById("text").style.color = bgColor;
      document.getElementById("author").style.color = bgColor;
    }

    return (
      <main id="main"  style={{height: "100vh", width: "100vw"}}>
        <div id="quote-box" style={{minHeight: "40vh", height: "fit-content" }} className="container-lg col-lg-6 col-md-6 col-sm-12 col-xs-6 d-flex justify-content-center align-items-center">
          <section className="bg-white text-center rounded p-5 mt-5" style={{width: "100%", height: "auto", boxSizing: "border-box"} }>
            <div id="text" className="fw-bold fs-2">
              "{text}.
            </div>
            <span id="author" className="d-block text-end lead">
              -{author}
            </span>
            <div className="d-flex justify-content-between align-items-center mt-5" >
              <div className="fs-1">
                <a href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(`"${text}" - ${author}`)}`} target="_blank" rel="noopener noreferrer" id="tweet-quote" className="text-decoration-none"><i className="bi bi-twitter"></i></a>
              </div>
              <button type="button" className="btn btn-success align-middle" id="new-quote" onClick={handleClick}>New Quote</button>
            </div>
          </section>
        </div>
        <div className="d-flex justify-content-center mt-5">quotes app</div>
      </main>
      
    )
  }
        const domContainer = document.querySelector('#root');
        const myRoot = ReactDOM.createRoot(domContainer)
        myRoot.render(<Myapp />);
    </script>
    
</body>
</html>
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
It seems like the issue is with importing the useEffect and useState hooks from the React package. You should not import those hooks separately, but rather import the entire React package and access the hooks through it.

Instead of: const { useEffect, useState } = React;
You should use: import React, { useEffect, useState } from 'react';
So the corrected import statement would look like this:

import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom';

Also, it seems like you are passing quotesArr as a prop to Myapp, but it is not needed as it is already declared globally. You can remove it from the Myapp component declaration:
const Myapp = () => { ... }

These changes should fix the issue you are facing.
 
Joined
Sep 12, 2022
Messages
39
Reaction score
0
It seems like the issue is with importing the useEffect and useState hooks from the React package. You should not import those hooks separately, but rather import the entire React package and access the hooks through it.

Instead of: const { useEffect, useState } = React;
You should use: import React, { useEffect, useState } from 'react';
So the corrected import statement would look like this:

import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom';

Also, it seems like you are passing quotesArr as a prop to Myapp, but it is not needed as it is already declared globally. You can remove it from the Myapp component declaration:
const Myapp = () => { ... }

These changes should fix the issue you are facing.
Using
import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom';
gives an error
caught ReferenceError: require is not defined
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
It seems like the issue is with importing the useEffect and useState hooks from the React package. You should not import those hooks separately, but rather import the entire React package and access the hooks through it.

Instead of:
const { useEffect, useState } = React;

You should use:

import React, { useEffect, useState } from 'react';

So the corrected import statement would look like this:

import React, { useEffect, useState } from 'react';

// Rest of the code
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,790
Messages
2,569,637
Members
45,346
Latest member
EstebanCoa

Latest Threads

Top