Home > Software engineering >  Why doesn't the onClick action add a value to an existing integer
Why doesn't the onClick action add a value to an existing integer

Time:03-07

I am using ReactJS Vite and Tailwind CSS and I'm trying to add 150 to the int "tokens" in a button (located in navbar), but I can't get it to work. Can anyoone help me? It is very simplyfied (using components in navbar.jsx and in main.jsx

Navbar.jsx (loaded into main.jsx)

import { Link } from "react-router-dom";
import React, { useState } from 'react';

var tokens = 100;
export default function Navbar() {
  return (
    <div>
      <nav >
        {/* tokens */}
          <div >
            <div >
              <button  onClick={()=>tokens =100}>Add Tokens</button>              
               <p
               
               >
                 {tokens} Tokens
              </p>
            </div>
          </div>

      </nav>
    </div>
  );
}

main.jsx (or

//import of libraries
import { render } from "react-dom";
import { BrowserRouter, Routes, Route,} from "react-router-dom";

//css (TailWind)
import './index.css'

//imports of pages
import App from "./App";
import Cases from "./routes/cases";
import Upgrader from "./routes/upgrader";
import Contracts from "./routes/contracts";
import Inventory from "./routes/inventory";
import Navbar from "./navbar"

//site content
const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
  <Navbar/>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="cases" element={<Cases />} />
      <Route path="upgrader" element={<Upgrader />} />
      <Route path="contracts" element={<Contracts />} />
      <Route path="inventory" element={<Inventory />} />
    </Routes>
  </BrowserRouter>,
  rootElement
);

CodePudding user response:

In order to use "useState" properly, you need to use this syntax:

export default function Navbar() {   

  const [tokens , setTokens] = useState(100)

    return (

Make sure to put your hook inside of your functional component.

Then update your onClick to utilze your hook:

onClick={()=>setTokens(tokens 100)}
  • Related