Home > Back-end >  How to handle React Hooks and Style Tags?
How to handle React Hooks and Style Tags?

Time:07-16

I started with React and try to create a webside with Python Flask React. So I created a Python Flask backend and React frontend and it worked to show items from backend to my frontend.

Now I found this tutorial to create a navbar at the left side of my webside

I tried it until 22:24, in this video: YouTube Tutorial but I don't know why it is working in tutorial and I receive errors with the same code. Can you help me?

My Problem is, that I receive this message in my browser:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
React 2
    resolveDispatcher
    useRef
    BrowserRouter index.tsx:151
    React 11
    renderWithHooks
    mountIndeterminateComponent
    beginWork
    callCallback
    invokeGuardedCallbackDev
    invokeGuardedCallback
    beginWork$1
    performUnitOfWork
    workLoopSync
    renderRootSync
    performConcurrentWorkOnRoot
workLoop scheduler.development.js:266
flushWork scheduler.development.js:239
performWorkUntilDeadline scheduler.development.js:533 react.development.js:1465

Sidebar.jsx:

import React from 'react';
import styled from 'styled-components';
import * as FaIcons from 'react-icons/fa';
import * as AiIcons from 'react-icons/ai';
import {Link} from "react-router-dom";


const Nav = styled.div`   
    background: #15171c;
    height: 80px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    `;

 const NavIcon = styled(Link)`    
    margin-left: 2rem;
    font-size: 2rem;
    height: 80px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    `;

const Sidebar = () => {
    return (
        <>
            <Nav>
                <NavIcon to='#'>
                    <FaIcons.FaBars />
                </NavIcon>
            </Nav>
        </>
    );
};

export default Sidebar;
    

App.js:

    import React, {useState, useEffect} from 'react';
    import Sidebar from './components/Sidebar';
    import './App.css';
    import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
    
    /**
     * useState = received backend_data   rendering
     * useEffect = fetch backend_API at first rendering
     * */
    
    function App() {
    
        const [data, setData] = useState([]);
    
        useEffect(() => {
            fetch("http://localhost:5000/menu").then(
                res => res.json()
            ).then(
                data => {
                    setData(data)
                    console.log(data)
                }
            )
        }, [])
    
        return (
            <div>
                <Router>
                    <Sidebar />
                </Router>
    
    
                {(typeof data.menu === 'undefined') ? (
                    <p>Loading...</p>
                ):(
                    data.menu.map((menu, i) => (
                        <p key={i}>{menu}</p>
                    ))
                )}
            </div>
        )
    }
    
    export default App

Package.json:

{
  "name": "react-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.4.0",
    "react-scripts": "5.0.1",
    "styled-components": "^5.3.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

CodePudding user response:

You're getting an error message - it points you to where the problem might be:

...
BrowserRouter index.tsx:151
...

Check line 151 of your index.tsx file or attach it to your post.

CodePudding user response:

The problem is, I don't know about a index.tsx Maybe it will be generated while browser compiling?

Here is my index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(

    <App />

);

And my index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>
  • Related